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
Search a word in a text file and return its frequency
提问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 Clyde Lobo
Read These
阅读这些
http://wiki.answers.com/Q/Write_a_Java_program_to_find_occurrences_of_given_word_in_a_text
http://wiki.answers.com/Q/Write_a_Java_program_to_find_occurrences_of_given_word_in_a_text
http://www.devdaily.com/java/edu/pj/pj010006/
http://www.devdaily.com/java/edu/pj/pj010006/
回答by dogbane
- Read each line in the file. See Tutorial | Reading, Writing, and Creating Files
- You can use string.containsto check if the line contains the word you are looking for
- increment an int counter if the word is found
- 读取文件中的每一行。见教程| 读取、写入和创建文件
- 您可以使用string.contains检查该行是否包含您要查找的单词
- 如果找到单词,则增加一个 int 计数器