使用java代码实现一个词频计算器统计某单词出现的频率具体代码
时间: 2023-03-13 07:29:07 浏览: 42
可以尝试下面的Java代码:String text = "put your text here";
String[] words = text.split("\\s+");
Map<String, Integer> wordCounts = new HashMap<String, Integer>();
for (String word : words) {
Integer count = wordCounts.get(word);
if (count == null) {
wordCounts.put(word, 1);
} else {
wordCounts.put(word, count + 1);
}
}
相关问题
使用java代码实现一个词频计算器统计某单词出现的频率
可以使用HashMap来实现一个词频计数器,首先将单词添加到HashMap中,然后使用for循环遍历整个字符串,并检查每个单词是否在HashMap中。如果存在,则将计数器加1,如果不存在,则将单词添加到HashMap中,并将计数器设置为1。
写一个词频统计的java代码
以下是一个简单的 Java 代码示例,用于词频统计:
```java
import java.util.HashMap;
import java.util.Map;
public class WordFrequencyCounter {
public static void main(String[] args) {
String text = "This is a sample text with words. This is a sample text with more words.";
// 将文本分割成单词
String[] words = text.split(" ");
// 创建一个 HashMap 来存储每个单词的出现次数
Map<String, Integer> wordCounts = new HashMap<>();
// 遍历每个单词,统计出现次数
for (String word : words) {
// 如果单词已经存在于 HashMap 中,则将其出现次数加1;否则,将其添加到 HashMap 中并将其出现次数设置为1。
if (wordCounts.containsKey(word)) {
int count = wordCounts.get(word);
wordCounts.put(word, count + 1);
} else {
wordCounts.put(word, 1);
}
}
// 输出每个单词的出现次数
for (String word : wordCounts.keySet()) {
int count = wordCounts.get(word);
System.out.println(word + " occurs " + count + " times.");
}
}
}
```
在上面的示例中,我们将文本分割成单词,并使用 HashMap 存储每个单词的出现次数。然后,我们遍历 HashMap,并输出每个单词的出现次数。