gpt4 book ai didi

java - 词频计数器,列表无法正常工作

转载 作者:行者123 更新时间:2023-11-30 10:48:36 26 4
gpt4 key购买 nike

我有一些代码可以计算给定单词 ArrayList 中的单词频率。我有一个频率类,它主要存储单词及其各自的频率。这是我的代码:

public static List<Frequency> computeWordFrequencies(List<String> words) {
List<String> wordsList = words;
String[] wordsArray = wordsList.toArray(new String[0]);
Arrays.sort(wordsArray);
Set<String> noDuplicates = new LinkedHashSet<>(Arrays.asList(wordsArray));
List<Frequency> frequencies = new ArrayList<>();
for (String word : noDuplicates) {
int wordFrequency = Collections.frequency(words, word);
Frequency newFrequency = new Frequency(word, wordFrequency);
System.out.println(newFrequency.toString());
frequencies.add(newFrequency);
}
for (Frequency f : frequencies) {
System.out.println(f.getText()+" "+f.getFrequency());
}
return frequencies;
}

供引用,频率等级:

public class Frequency {

private final String word;
private static int frequency;

public Frequency(String word) {
this.word = word;
frequency = 0;
}

public Frequency(String word, int newfrequency) {
this.word = word;
this.frequency = newfrequency;
}

public String getText() {
return word;
}

public int getFrequency() {
return frequency;
}

public static void setFrequency(int newFrequency) {
frequency = newFrequency;
}

public void incrementFrequency() {
frequency++;
}

@Override
public String toString() {
return word + ":" + frequency;
}

}

我在我的代码中插入了 print 语句,这是一些输出:

wrapping:1 yard:3 yarn:2 year:2 yet:1 yukon:1 zero:2 abandoned
2 accordion 2 acequia 2 across
2 added 2

所以当创建频率时,它们具有正确的频率,但不知何故它们后来都变成了 2。更奇怪的是,如果我将第二个打印语句更改为 f.toString(),即使是第一个打印语句只显示 2 个这样的频率:

rising:2 river:2 riveredge:2 riversound:2 road:2 roadrunners:2 roadside:2 roast:2

谁能告诉我为什么所有频率都设置为 2,或者问题出在哪里?

最佳答案

删除 static来自

private static int frequency

您希望每个单词都有一个单独的实例变量,而不是所有单词都有一个类变量。


另外,我会推荐 Hashmap<String, Integer>对于频率计数器而不是创建任何包装对象,因为......

  1. 没有理由将列表转换为数组,然后转换为集合,然后再转换回列表
  2. 在删除重复项之前不需要对列表进行排序
  3. Collections.frequency一个循环内的运行时间为 O(n^2)

关于java - 词频计数器,列表无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35739081/

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