0

我正在开发一个程序,我正在读取文件并提取关键字及其计数。稍后我需要选择频率最高的单词并将它们与关键字匹配。

我已将在文件中找到的所有关键字存储在字符串列表中。我希望根据频率对这些进行排序。因此,如果在索引 17 处我有一个单词“stack”,并且其他整数列表中索引 17 处的值最大,我希望将它们带到位置 1。

我可以使用 collections.sort 对这些进行排序,但它不会处理其他列表。

这是我的代码:

while(m.find()) 
    {
        if(keyword.contains(m.group()))
            {
            keywordcount.set(keyword.indexOf(m.group()),keywordcount.get(keyword.indexOf(m.group()))+1);
            //System.out.println("*"+m.group()+":"+keywordcount.get(keyword.indexOf(m.group())));
            }
        else
            {
            keyword.add(m.group());
            int var=keyword.indexOf(m.group());
            //System.out.println(m.group()+":"+var);
            keywordcount.add(var, 1);
            }
        //System.out.println(keyword.size()+"#"+keywordcount.size());                       
    }
    for(int i=0;i<keyword.size();i++)
    {
        System.out.print(keyword.get(i)+ ":" +keywordcount.get(i)+" ");
    }
4

3 回答 3

5

通常,人们会将 theString和 theInteger放在一个类中,然后对该类的实例列表进行排序。

例如

class StringCount implements Comparable<StringCount> {
    private final String string;
    private final int count;

    public StringCount(String string, int count) {
        this.string = string;
        this.count = count;
    }

    @Override
    public int compareTo(StringCount right) {
        return this.count < right.count ? -1
             : this.count > right.count ? 1
             : 0;
    }

    // implement equals and hashCode too
    // if a.compareTo(b) == 0, then a.equals(b) should return true.

}

然后,您可以创建一个List<StringCount>并调用Collections.sort(stringCountList).

请注意,这会将具有最低StringCount值的实例放在首位,因此它们按升序排列。

于 2012-04-19T12:05:48.350 回答
1
final List<String> words = new ArrayList<>();
final Map<String, Integer> frequencies = new HashMap<>();

while (m.find())  {
    String word = ...extract the word from m...;

    if (!words.contains(word)) words.add(word);

    if (!frequencies.contains(word)) frequencies.put(word, 1);
    else frequencies.put(word, frequencies.get(word) + 1);
}

Collections.sort(words, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        int f1 = frequencies.get(s1);
        int f2 = frequencies.get(s2);
        if (f1 < f2) return 1;
        if (f1 > f2) return -1;
        return 0;
    }
});
于 2012-04-19T12:14:04.523 回答
1

这可能是检查multisets的理想时机。

支持顺序无关相等的集合,如 Set,但可能有重复元素。多重集有时也称为包。

多重集合中彼此相等的元素称为相同单个元素的出现。一个元素在多重集中出现的总数称为该元素的计数(术语“频率”和“多重性”是等价的,但在此 API 中不使用)。由于元素的计数表示为 int,因此多重集可能永远不会包含超过 Integer.MAX_VALUE 出现的任何一个元素。

于 2012-04-19T12:44:11.640 回答