Java案例:統計單詞個數
一、文本文件test.txt
二、建立Java項目JavaWordCount實現詞頻統計
package net.hw.wc; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashMap; import java.util.Map; /** * Created by howard on 2018/2/6. */ public class WordCount { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("test.txt")); Map<String, Integer> map = new HashMap<>(); String nextLine = ""; while ((nextLine = br.readLine()) != null) { String[] data = nextLine.split(" "); for (String word : data) { map.put(word, map.containsKey(word) ? map.get(word) + 1 : 1); } } for (String key : map.keySet()) { System.out.println(key + ": " + map.get(key)); } } }
三、運行程序,查看結果
本文分享 CSDN - howard2005。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。java