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+"個單詞");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM