- 编程实现
- 创建WordCount 遍历文件
- 在项目里创建一个单词文本文件words.txt
运行程序,
- 拆分
运行程序,
- 针对每行单词数组进行词频统计
运行程序,
- 按照指定格式输出词频统计结果
public class WordCount {
public static void main(String[] args) throws Exception {
// 定义缓冲字符流
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
// 定义词频统计哈希印射
Map wc = new HashMap<>();
// 定义行字符串变量
String nextLine = "";
// 读取文件遍历所有行
while ((nextLine = br.readLine()) != null){
// 按空格拆分,得到单词数组
String[] words = nextLine.split(" ");
// 遍历单词数组,进行单词计数
for (String word : words) {
wc.put(word, wc.containsKey(word)? wc.get(word) + 1 : 1);
}
}
// 按照指定格式输出词频统计结果
for (String key : wc.keySet()) {
System.out.println("(" + key + "," + wc.get(key) + ")");
}
}
}
运行程序,



