Lev*_*007 3 java python-3.x kotlin
我想编写一个程序,例如显示文本中重复次数最多的 5 个单词。保存在地图中的文本的单词,其键是单词,其值是重复该单词的次数。
该程序显示重复最多的单词,但我不知道如何改进以显示 5 个重复最多的单词(以及如何使用地图而不是列表)。
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class MostRepeatedWord {
public static void main(String[] args) throws Exception {
String line, word = "";
int count = 0, maxCount = 0;
ArrayList<String> words = new ArrayList<String>();
//Opens file in read mode
FileReader file = new FileReader("data.txt ");
BufferedReader br = new BufferedReader(file);
//Reads each line
while((line = br.readLine()) != null) {
String string[] = line.toLowerCase().split("([,.\\s]+) ");
//Adding all words generated in previous step into words
for(String s : string){
words.add(s);
}
}
//Determine the most repeated word in a file
for(int i = 0; i < words.size(); i++){
count = 1;
//Count each word in the file and store it in variable count
for(int j = i+1; j < words.size(); j++){
if(words.get(i).equals(words.get(j))){
count++;
}
}
//If maxCount is less than count then store value of count in maxCount
//and corresponding word to variable word
if(count > maxCount){
maxCount = count;
word = words.get(i);
}
}
System.out.println("Most repeated word: " + word);
br.close();
}
}
Run Code Online (Sandbox Code Playgroud)
这是函数式风格可以导致代码更短的情况之一 - 希望更容易理解!
获得words列表后,您可以简单地使用:
words.groupingBy{ it }
.eachCount()
.toList()
.sortedByDescending{ it.second }
.take(5)
Run Code Online (Sandbox Code Playgroud)
在groupingBy()创建分组从单词列表。(通常情况下,你给一键选择功能,讲解如何组的项目,但在这种情况下,我们要的话自己,因此it)。由于我们只关心数字出现,eachCount()得到计数。(感谢 Ilya 和 Tenfour04 的那部分。)
然后我们将地图转换成一个列表,准备好进行排序。该列表由成对组成,单词作为第一个值,计数作为第二个值。
所以sortedByDescending{ it.second }按计数排序。因为我们按降序排序,所以它首先给出最常用的词。
最后,take(5)从列表中获取前五个值,这将是五个最常见的单词(以及它们的计数)。
例如,当我在几个简单的句子上运行它时,它给出:[(the, 4), (was, 3), (it, 3), (a, 2), (of, 2)].
(如果您只想要单词,而不是计数,则可以使用.map{it.first}。另外,正如 Tenfour04 所建议的,有更好的方法可以从文本中提取单词;但是一旦您开始考虑大小写、撇号、连字符、非-ASCII 字母等——这似乎是一个与获取最常见单词不同的问题。)
| 归档时间: |
|
| 查看次数: |
964 次 |
| 最近记录: |