Java查找统计一个文档中的单词个数

统计txt文档下的英文单词及个数。

package com.zit;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Day02 {
    public static void main(String[] args){
        int count = 0;
        File f = new File("d:/text.txt");
        String s = "";
        StringBuffer sb = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(f));
            while((s=br.readLine())!=null){
            sb.append(s+'\n');
            }br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Pattern p = Pattern.compile("\\b[a-zA-Z]+\\b");
        Matcher m = p.matcher(sb.toString());
        while(m.find()){
            System.out.println(m.group());
            count++;
        }
        System.out.println("总共"+count+"个单词");
    }
}

猜你喜欢

转载自www.cnblogs.com/zxwen/p/9544671.html