- 词频统计
- 编程实现
· 参看本博《经典案例【词频统计】十一种实现方式》
· 针对单词文本文件,统计每个单词出现的次数
hello hadoop hello spark i love you hadoop and spark i learn hadoop and scala编程实现
· 在项目根目录里创建单词文本文件 - words.txt
在p03建好t08子包再建WordCount
package p03.t08;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
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) {
System.out.println(nextLine);
//按空格拆分,得到单词组
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) + ")");
}
}
}
· 将文件行按空格拆分成单词数组
· 针对每行单词数组进行词频统计
· 按指定格式输出词频统计结果
package p03.t08;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
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) + ")");
}
}
}



