编写一个Java程序,用来统计某名著中字词的出现频率,建议使用特定的数据集合,并说明算法原理。
时间: 2024-02-13 11:06:15 浏览: 42
算法原理:
1. 读取文件,将文件内容转换成字符串。
2. 将字符串按照空格分割成单词数组。
3. 遍历单词数组,统计每个单词出现的频率。
4. 将单词和频率存储在HashMap中。
Java代码示例:
```java
import java.util.*;
public class WordFrequencyCounter {
public static void main(String[] args) {
// 读取文件内容
String text = "this is a test text. this is another test text.";
// 将字符串按照空格分割成单词数组
String[] words = text.split(" ");
// 统计单词的出现频率
Map<String, Integer> wordFreq = new HashMap<>();
for (String word : words) {
Integer freq = wordFreq.get(word);
wordFreq.put(word, freq == null ? 1 : freq + 1);
}
// 输出单词出现的频率
for (Map.Entry<String, Integer> entry : wordFreq.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
```
以上代码使用HashMap来统计单词的出现频率,时间复杂度为O(n),其中n为单词的数量。