我正在构建一个基本的词频计数器。代码如下:
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”,但如果这样做,我会遇到其他问题,例如重复添加单词。我的逻辑在这里吗?这个项目会有更好的方法吗?提前致谢!