gpt4 book ai didi

java - 逻辑java的词频计数器问题

转载 作者:行者123 更新时间:2023-12-02 00:03:51 25 4
gpt4 key购买 nike

我正在构建一个基本的词频计数器。代码如下:

public static List<Frequency> computeWordFrequencies(List<String> words) 
{
List<Frequency> list_of_frequency = new ArrayList<Frequency>();
List<String> list_of_words = words;
int j = 0;
for(int i=0; i<list_of_words.size(); i++)
{

String current_word = list_of_words.get(i);
boolean added = false;
if(list_of_frequency.size() == 0)
{
list_of_frequency.add(new Frequency(current_word, 1));
System.out.println("added " + current_word);
}
else
{

System.out.println("Current word: " + current_word);
System.out.println("Current Frequency: " + list_of_frequency.get(j).getText());
if(list_of_frequency.contains(current_word))
{
list_of_frequency.get(j).incrementFrequency();
System.out.println("found... incremented " + list_of_frequency.get(j).getText() + " frequency");
added = true;
}
else
{
list_of_frequency.add(new Frequency(current_word, 1));
System.out.println("added " + current_word);
added = true;
}
}
}
}

我得到的输出是:

added I
Current word: am
Current Frequency: I
added am
Current word: very
Current Frequency: I
added very
Current word: good
Current Frequency: I
added good
Current word: at
Current Frequency: I
added at
Current word: being
Current Frequency: I
added being
Current word: good
Current Frequency: I
added good
Total item count: 7
Unique item count: 7
I:1
am:1
very:1
good:1
at:1
being:1
good:1

所以我需要一个 for 循环来遍历“list_of_Frequency”,但如果我这样做,我会遇到其他问题,例如重复添加单词。我的逻辑是否正确?是否有更好的方法来完成这个项目?提前致谢!

最佳答案

您可以使用frequency来做到这一点Collections 类的方法

这是一个示例:

public void wordFreq(){
String text = "hello bye hello a bb a bye hello";

List<String> list = Arrays.asList(text.split(" "));

Set<String> uniqueWords = new HashSet<String> (list);
for (String word : uniqueWords) {
System.out.println(word + ": " + Collections.frequency(list, word));
}
}

关于java - 逻辑java的词频计数器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14298566/

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