java - 使用 HashMap 计算文档频率 [Java]

标签 java hashmap

我正在尝试计算文档频率(即每个单词出现在多少个文档中),例如:

Doc1:这款手机是有史以来最伟大的手机。
Doc2:您的电话号码是多少。

结果:

this              1
phone             2
is                1
the               1
ever              1
what's            1
your              1
number            1

我有以下 Java 代码

HashMap<String, String> wordDoc = new HashMap<String, String>();
HashMap<String, Integer> countDfIndex = new HashMap<String, Integer>();

if (!wordDoc.containsKey(word)) {
    wordDoc.put(word,docno);
    countDfIndex.put(word, 1);
}
if (wordDoc.get(word)!=null) {
    if(!wordDoc.containsValue(docno)) {
        wordDoc.put(word,docno);
        countDfIndex.put(word, countDfIndex.get(word)+1);
    }
}

我没有得到正确的结果,请帮忙!!

最佳答案

我假设您正在尝试计算包含相应单词的文档数量,而不是出现的总数。

如果是这样:

Map<String, Integer> countDfIndex = new HashMap<String, Integer>();

for (... document : documents) {
    Set<String> alreadyAdded = new HashSet<String>(); // new empty set for each document

    ...

    if (!alreadyAdded.contains(word)) {
        if (!countDfIndex.containsKey(word) {
            countDfIndex.put(word, 1);
        } else {
            countDfIndex.put(word, countDfIndex.get(word) + 1);
        }
        alreadyAdded.add(word); // don't add the word anymore if found again in the document
    }

}

关于java - 使用 HashMap 计算文档频率 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36399399/

相关文章:

java - 选择选项后无法创建输入文本框

java - 将 XML 粘贴到我的 IDE 中并对其进行格式化

hadoop - 在Hadoop中合并两个SortedMapWritable?

java - 大型 HashMap 的初始容量和 LoadFactor 的用户定义值?

java - HashMap JDK8 中的方法 putTreeVal()

Java - BufferedImage - 每次迭代后清除屏幕

java - Hibernate DELETE查询错误导致: com. mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:表 'gestcart.loanpersonrelation'不存在

Java Swing 依赖注入(inject)

hashmap - 模式匹配选项时引用具有不兼容类型的匹配臂时抛出错误

java - 如何克服 freemarker 树集按字母顺序排序 int 键?