統計檔案中單詞出現的頻次
public class Util{ public static void main(String[] args) throws IOException { //鍵盤錄入指定檔名 Scanner sc = new Scanner(System.in); String fileName = sc.nextLine();
//呼叫方法,求結果 countWord(fileName); }
public static void countWord(File filename) throws IOException { Util util = new Util(); String[] str = util.readFile(filename); Map<String,Integer> map = new HashMap<String,Integer>(); //遍歷陣列(即整篇文章) for(String word : str){ if(map.containsKey(word)){ //包含該單詞則加1 map.put(word, map.get(word)+1); }else{ //第一次出現則為1 map.put(word, 1); } } util.printCount(map); } public String[] readFile(File filename) throws IOException { Reader reader = new FileReader(filename); //BufferedReader可以讀取行,讀取速度快 BufferedReader br = new BufferedReader(reader); //用於將讀取的每一句拼接,去除邊緣截斷單詞 StringBuffer sbu = new StringBuffer(); String line = ""; while (null != (line = br.readLine())) { //拼接行 sbu.append(line); } // System.out.println(sbu); String s = sbu.toString(); //正則中的非英文字元分割 String[] str = s.split("\\W"); return str; }
//列印方法 public void printCount(Map map) { Set<String> set = map.keySet(); for (String key : set) { String str = key + "——>" + map.get(key); System.out.println(str); } } }