JAVA词频统计使用hashmap代码怎么写
时间: 2024-05-01 20:18:52 浏览: 130
我可以为您提供一个JAVA词频统计使用hashmap的代码示例:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
File file = new File("filename.txt"); // 替换为你要统计的文件名
Map<String, Integer> wordCount = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split("\\s");
for (String word : words) {
Integer count = wordCount.get(word);
if (count == null) {
wordCount.put(word, 1);
} else {
wordCount.put(word, count + 1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
```
以上代码会读取指定文件,使用HashMap来统计单词出现的频率,最后输出结果。
阅读全文