標籤:
參考網上的代碼,自己再略微修改,純作記錄
import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;public class readFile { public static void main(String[] args) { int lineNum = 0;//定義變數 行數 HashMap<String,Integer> map = new HashMap<String ,Integer>();//定義map,用於儲存文本中的單詞和出現次數 BufferedReader in = null; try { in = new BufferedReader(new FileReader("F:\\EC.txt"));//文本地址 String buffer = null; // while((buffer = in.readLine()) != null) { lineNum++;
String[] words = buffer.replaceAll("[^a-zA-Z]+", " ").trim().split(" ");//Regex分割 for(int i = 0; i < words.length; i++) { map.put(words[i],map.getOrDefault(words[i], 0)+1);//value預設為0,每重複1次加1 } } //本段為輸出map中儲存的資料 Set<Map.Entry<String,Integer>> set = map.entrySet(); for(Iterator<Map.Entry<String,Integer>> it = set.iterator();it.hasNext();) { Map.Entry<String,Integer> entr = (Map.Entry<String,Integer>)it.next(); System.out.println(entr.getKey()+"--------"+entr.getValue()); } System.out.println("行數"+lineNum); System.out.println("字數"+map.size()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { in.close();//關閉緩衝字元流
} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
Java讀本地英文txt文本,顯示行數、字數、單詞出現頻率