我无法弄清楚如何为程序找到最频繁出现的单词和最频繁出现的不区分大小写的单词。我有一个扫描仪,可以读取文本文件和一个 while 循环,但仍然不知道如何实现我要查找的内容。我是否使用不同的字符串函数来读取和打印单词?
这是我目前的代码:
public class letters {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("input.txt");
Scanner scanner = new Scanner(fis);
String word[] = new String[500];
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
}
}
String []roll = s.split("\\s");
for(int i=0;i<roll.length;i++){
String lin = roll[i];
//System.out.println(lin);
}
}
这就是我目前所拥有的。我需要输出说:
Word:
6 roll
Case-insensitive word:
18 roll
这是我的输入文件:
@
roll tide roll!
Roll Tide Roll!
ROLL TIDE ROLL!
ROll tIDE ROll!
roll tide roll!
Roll Tide Roll!
ROLL TIDE ROLL!
roll tide roll!
Roll Tide Roll !
@
65-43+21= 43
65.0-43.0+21.0= 43.0
65 -43 +21 = 43
65.0 -43.0 +21.0 = 43.0
65 - 43 + 21 = 43
65.00 - 43.0 + 21.000 = +0043.0000
65 - 43 + 21 = 43
我只需要它找到出现次数最多的单词(最大连续字母序列)(即 roll)并打印出它出现的次数(即 6)。如果有人可以帮助我解决这个问题,那就太好了!谢谢
最佳答案
考虑使用 Map<String,Integer>
对于单词,那么您可以实现它来计算单词数量,并且适用于任意数量的单词。 See Documentation for Map .
像这样(需要修改不区分大小写)
public Map<String,Integer> words_count = new HashMap<String,Integer>();
//read your line (you will have to determine if this line should be split or is equations
//also just noticed that the trailing '!' would need to be removed
String[] words = line.split("\\s+");
for(int i=0;i<words.length;i++)
{
String s = words[i];
if(words_count.ketSet().contains(s))
{
Integer count = words_count.get(s) + 1;
words_count.put(s, count)
}
else
words_count.put(s, 1)
}
然后你有字符串中每个单词的出现次数,为了得到出现次数最多的,可以做类似的事情
Integer frequency = null;
String mostFrequent = null;
for(String s : words_count.ketSet())
{
Integer i = words_count.get(s);
if(frequency == null)
frequency = i;
if(i > frequency)
{
frequency = i;
mostFrequent = s;
}
}
然后打印
System.out.println("The word "+ mostFrequent +" occurred "+ frequency +" times");
关于java - 您如何在文本文件中查找单词并打印使用数组显示的最频繁的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18626233/