java 在文本文件中搜索一个词并返回它的频率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5102044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:26:44  来源:igfitidea点击:

Search a word in a text file and return its frequency

java

提问by Wai Loon II

How to search for a particular word in a text file containing texts of words and return its frequency or occurrences ?

如何在包含单词文本的文本文件中搜索特定单词并返回其频率或出现次数?

回答by aioobe

Using a Scanner:

使用扫描仪:

String text = "Question : how to search for a particular word in a " +
        "text file containing texts of words and return its " +
        "frequency or occurrences ?";

String word = "a";

int totalCount = 0;
int wordCount = 0;
Scanner s = new Scanner(text);
while (s.hasNext()) {
    totalCount++;
    if (s.next().equals(word)) wordCount++;
}

System.out.println("Word count:  " + wordCount);
System.out.println("Total count: " + totalCount);
System.out.printf("Frequency:   %.2f", (double) wordCount / totalCount);

Output:

输出:

Word count:  2
Total count: 24
Frequency:   0.08

回答by dogbane