gpt4 book ai didi

java - 在 Java 中转换 ArrayList

转载 作者:行者123 更新时间:2023-12-02 11:42:56 25 4
gpt4 key购买 nike

我有以下代码,用于计算并显示每个单词在整个文本文档中出现的次数。

try {
List<String> list = new ArrayList<String>();
int totalWords = 0;
int uniqueWords = 0;
File fr = new File("filename.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
for (int i = 0; i < space.length; i++) {
list.add(space[i]);
}
totalWords++;
}
System.out.println("Words with their frequency..");
Set<String> uniqueSet = new HashSet<String>(list);
for (String word : uniqueSet) {
System.out.println(word + ": " + Collections.frequency(list,word));
}
} catch (Exception e) {

System.out.println("File not found");

}

是否可以修改此代码,使其只对每行而不是整个文档中的每个出现次数进行计数?

最佳答案

可以读取每行的内容,然后应用每行的逻辑来计算单词数:

   File fr = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);

// Read the line in the file
String line = null;
while ((line = br.readLine()) != null) {
//Code to count the occurrences of the words

}

关于java - 在 Java 中转换 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405727/

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