博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

抽取文章单词

Posted on 2015-03-14 20:14  ShangYT  阅读(943)  评论(0)    收藏  举报

package com.***.helper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;

/**
 * http://bbs.csdn.net/topics/390998324?page=1#post-398977511<br>
 * 假设要读取一个TXT文件 内容包括各种括号 逗号 斜杠 “--” 数字 和单词 <br>
 * 但只取单词 并 存进 arraylist <br>

 * 文件来源:http://www.k8.hk/1.txt
 *
 * @author ***
 * @date 2015年3月14日 下午7:41:12
 */
public class ReadWords {

    public static void main(String[] args) throws IOException {

        String fileName = "/Users/***/workspace/***_demo/***/src/main/java/com/***/helper/1.txt";
        List<String> lines = FileUtils.readLines(new File(fileName));
        List<String> result = analysisWords(lines);
        FileUtils.writeLines(new File(fileName + ".result"), result);
    }

    public static List<String> analysisWords(List<String> lines) {
        List<String> result = new ArrayList<String>();
        for (String line : lines) {
            List<String> tmp = analysisWords(line);
            result.addAll(tmp);
        }
        return result;
    }

    public static List<String> analysisWords(String line) {
        List<String> result = new ArrayList<String>();
        String r = "";
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            // 不是字母,清空缓存(当前单词);是字母,继续追加当前单词
            if (!isLetter(c)) {
                // 过滤空白字符串
                if (r.trim().length() > 0) {
                    result.add(r);
                }
                r = "";
            } else {
                r += c;
            }
        }
        return result;
    }

    private static boolean isLetter(char c) {
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
            return true;
        } else {
            return false;
        }
    }

}