java如何在文本中找到最常用的单词?
我有个问题。如果我有这样的输入: “谢谢你的车” 输出为“谢谢”。如果我的单词以大写字母开头,它将以小写字母打印该单词。 我可以为解决该问题的解决方案添加哪些内容
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);
}
# 1 楼答案
要让代码以输入的格式而不是小写打印最常用的单词,可以在代码行下方进行更改
将其更改为:
<强>但然后意识到{{CD1>}方法是 >敏感的,不会把“谢谢”和“谢谢”当作同一个词。>P/>
# 2 楼答案