【问题标题】:Comparing hashmap key with words in text file and updating value将 hashmap 键与文本文件中的单词进行比较并更新值
【发布时间】:2012-06-07 20:18:11
【问题描述】:

我一直在使用哈希图来存储文本文件中的唯一单词。现在,我需要将 hashmap 中的每个单词与另一个更大的文本文件进行比较,并跟踪每个单词在文本文件中出现的频率。

首先添加到 hashmap 时,我只插入键并将值设置为 0。我的计划是使用 'value' 作为较大文本文件中每个单词的频率。

我的尝试如下;我首先使用扫描仪读取原始文件并将单词存储到哈希图中。接下来,我再次使用扫描仪,但这次与更大的文本文件相关联。从这里开始,我有点卡住了。我不知道如何更新“值”并索引“键”。

这就是我所拥有的;

Scanner fileScanner = new Scanner (new File (fileName));
fileScanner.useDelimiter (" ");

while (fileScanner.hasNext()) {
    for (int i = 0; i < hashmap.size(); i++) {   //This I use to index the key field
        if (hashmap.get(i).equals(fileScanner.next().toString()) {
            int freq ++;
            //How do I update the value field of the corresponding value?
        }
    }
}

现在,显然,上述代码中的任何内容都不起作用,而且我在想办法时遇到了一些问题。谁能帮帮我?

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    您的地图应该是Map&lt;String, Integer&gt;:对于每个单词,您都有一个整数来存储单词的出现次数。

    获取单词出现的次数:Integer numberOfOccurrences = map.get(word);

    测试单词是否在地图中:if (numberOfOccurrences != null)

    增加出现次数:numberOfOccurrences++;

    要在地图中存储这个新值:map.put(word, numberOfOccurrences);

    没有理由迭代地图。您逐字阅读文件,并使用上述内容来增加每个单词的出现次数。

    【讨论】:

    • 非常感谢,感谢您的帮助
    【解决方案2】:

    如果您尝试计算单词的数量并将其存储为地图,那么在添加新单词时尝试将值 1 而不是 0(单词至少存在一次)。

    为了更新检查 map 是否包含 key 的值,然后再次将它的值增加。旧值将被替换。

    试试这个

    HashMap<String, Integer> hashmap = new HashMap<String, Integer>();
    String key = "myWord";
    hashmap.put(key, 1);
    Integer tmp = null;
    // lets increment value if exist in map or put new value if doesn't exits in map
    if ((tmp = hashmap.get(key)) != null) {
        //if map contains word
        hashmap.put(key, tmp + 1);
    } else {
        //if word is new, map does't contain it as key 
        hashmap.put(key, 1);
    }
    System.out.println(hashmap);
    //out ->{myWord=2}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2022-01-17
      • 2021-12-13
      • 1970-01-01
      • 2015-01-30
      相关资源
      最近更新 更多