gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:36:15 27 4
gpt4 key购买 nike

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

最佳答案

使用扫描仪:

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);

输出:

Word count:  2
Total count: 24
Frequency: 0.08

关于java - 在文本文件中搜索一个词并返回它的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5102044/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com