如何使用 bufferedreader 和 treemap 打印文本中出现频率最高的单词? - Java
How can I print the most frequent word in a text using bufferedreader and treemap ? - Java
文本将只包含空格和单词。
示例输入:
thanks for the help \n
the car works now \n
thanks \n
输出:
- 因为它的字典序小于“谢谢”。
public class Main {
public static void main(String[] args) throws IOException {
String line;
String[] words = new String[100];
Map < String, Integer > frequency = new HashMap < > ();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) {
words = line.split("\W+");
for (String word: words) {
String processed = word.toLowerCase();
processed = processed.replace(",", "");
if (frequency.containsKey(processed)) {
frequency.put(processed,
frequency.get(processed) + 1);
} else {
frequency.put(processed, 1);
}
}
}
}
int mostFrequentlyUsed = 0;
String theWord = null;
for (String word: frequency.keySet()) {
Integer theVal = frequency.get(word);
if (theVal > mostFrequentlyUsed) {
mostFrequentlyUsed = theVal;
theWord = word;
} else if (theVal == mostFrequentlyUsed && word.length() <
theWord.length()) {
theWord = word;
mostFrequentlyUsed = theVal;
}
}
System.out.printf(theWord);
}
}
我没有通过一次测试,我真的不知道为什么这就是我需要另一种方法的原因。
在你的问题标题中你提到了 TreeMap 但你实际上并没有使用它。
如果将实例化地图的行替换为
NavigableMap < String, Integer > frequency = new TreeMap < > ();
然后您可以用对地图的单个查询替换 for 循环:
System.out.println(frequency.lastEntry().key)
您可以在此处阅读文档:https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#lastEntry--
文本将只包含空格和单词。
示例输入:
thanks for the help \n
the car works now \n
thanks \n
输出: - 因为它的字典序小于“谢谢”。
public class Main {
public static void main(String[] args) throws IOException {
String line;
String[] words = new String[100];
Map < String, Integer > frequency = new HashMap < > ();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) {
words = line.split("\W+");
for (String word: words) {
String processed = word.toLowerCase();
processed = processed.replace(",", "");
if (frequency.containsKey(processed)) {
frequency.put(processed,
frequency.get(processed) + 1);
} else {
frequency.put(processed, 1);
}
}
}
}
int mostFrequentlyUsed = 0;
String theWord = null;
for (String word: frequency.keySet()) {
Integer theVal = frequency.get(word);
if (theVal > mostFrequentlyUsed) {
mostFrequentlyUsed = theVal;
theWord = word;
} else if (theVal == mostFrequentlyUsed && word.length() <
theWord.length()) {
theWord = word;
mostFrequentlyUsed = theVal;
}
}
System.out.printf(theWord);
}
}
我没有通过一次测试,我真的不知道为什么这就是我需要另一种方法的原因。
在你的问题标题中你提到了 TreeMap 但你实际上并没有使用它。
如果将实例化地图的行替换为
NavigableMap < String, Integer > frequency = new TreeMap < > ();
然后您可以用对地图的单个查询替换 for 循环:
System.out.println(frequency.lastEntry().key)
您可以在此处阅读文档:https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#lastEntry--