gpt4 book ai didi

Java:计算特定单词的频率并写入文件

转载 作者:行者123 更新时间:2023-11-30 10:44:22 25 4
gpt4 key购买 nike

我想读取文件夹中的所有文本文件并计算每个文件中的特定单词,然后将单词的频率写入 txt 文件。这是我的代码:

public static void main(String[] args) throws IOException{

String[] array = new String[]{"beautiful", "good", "extraordinary", "wonderful", "like",
"proud","brilliant","great","well", "perfect"};
int[] wordCount = new int[]{0,0,0,0,0,0,0,0,0,0};

File path = new File("development/text");

for(File file: path.listFiles()){

PrintWriter writer = new PrintWriter(new FileWriter("result.txt",true));
FileInputStream fin = new FileInputStream(file);
Scanner s = new Scanner(fin);

for(int i = 0; i < array.length; i++)
{
wordCounter = 0;
while (s.hasNext())
{
if (s.next().equals(array[i])) {
wordCount[i]++;
}
}
}

writer.println(wordCount[0] + "," + wordCount[1] + "," + wordCount[2] + "," +
wordCount[3] + "," + wordCount[4] + "," +wordCount[5] + "," +wordCount[6]
+ "," +wordCount[7] + "," + wordCount[8] + "," + wordCount[9]);
fin.close();
s.close();
writer.close();
}
}

但是,我的代码只读取数组的第一个元素(漂亮)。其他元素输出为 0,尽管它们出现在文本文件中。

最佳答案

反转循环的顺序。与其“针对数组中的每个单词,逐个单词地读取文件并查看是否存在匹配项”,不如“针对文件中的每个单词,对照数组中的每个单词进行检查”。

您当前实现的问题是它不会“倒回”文件。一旦第一个单词到达文件末尾,就无法返回文件并从头开始。然而,从文件的开头开始比从数组的开头开始开销要大得多,因此反转循环顺序是最优的解决方案:

while (s.hasNext()) {
String word = s.next();
for(int i = 0; i < array.length; i++) {
if (word.equals(array[i])) {
wordCount[i]++;
}
}
}

关于Java:计算特定单词的频率并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37415166/

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