【问题标题】:Google Guava MultiSet returning incorrect valueGoogle Guava MultiSet 返回不正确的值
【发布时间】:2014-02-23 04:02:26
【问题描述】:

我正在使用 Google Guava API 来计算字数。

public static void main(String args[])
    {
        String txt = "Lemurs of Madagascar is a reference work and field guide giving descriptions and biogeographic data for all the known lemur species in Madagascar (ring-tailed lemur pictured). It also provides general information about lemurs and their history and helps travelers identify species they may encounter. The primary contributor is Russell Mittermeier, president of Conservation International. The first edition in 1994 received favorable reviews for its meticulous coverage, numerous high-quality illustrations, and engaging discussion of lemur topics, including conservation, evolution, and the recently extinct subfossil lemurs. The American Journal of Primatology praised the second edition's updates and enhancements. Lemur News appreciated the expanded content of the third edition (2010), but was concerned that it was not as portable as before. The first edition identified 50 lemur species and subspecies, compared to 71 in the second edition and 101 in the third. The taxonomy promoted by these books has been questioned by some researchers who view these growing numbers of lemur species as insufficiently justified inflation of species numbers.";

        Iterable<String> result = Splitter.on(" ").trimResults(CharMatcher.DIGIT)
                   .omitEmptyStrings().split(txt);
        Multiset<String> words = HashMultiset.create(result);

        for(Multiset.Entry<String> entry : words.entrySet())
        {
            String word = entry.getElement();
            int count = words.count(word);
            System.out.printf("%S %d", word, count);
            System.out.println();
        }
    }

输出应该是

Lemurs 3

但是我是这样的:

Lemurs 1
Lemurs 1
Lemurs 1

我做错了什么?

【问题讨论】:

    标签: java guava word-count multiset


    【解决方案1】:

    MultiSet 工作正常。仔细查看您的结果 - 将 printf 切换为例如"|%S| %d" 会有所帮助:

    |lemurs.| 1
    |lemurs| 1
    |Lemurs| 1
    

    很明显,这些都是 3 个不同的字符串。这种情况下的解决方案是简单地去除所有非字母字符,并将所有单词小写。

    【讨论】:

      【解决方案2】:

      将printf("%S %d", words, count) 与大写S 一起使用隐藏了“狐猴”一词的不同大小写被分别计算的细节。当我运行该程序时,我看到了

      • “狐猴”的出现。句号没有被修剪
      • “狐猴”出现一次,全部小写
      • 出现第一个字母大写的“狐猴”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-09
        • 2021-10-26
        • 2015-10-13
        • 2014-12-06
        相关资源
        最近更新 更多