2012-06-03 61 views
1

我一直使用散列圖來存儲文本文件中的唯一單詞。現在,我需要將散列表中的每個單詞與另一個更大的文本文件進行比較,並跟蹤每個單詞出現在文本文件中的頻率。將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? 
     } 
    } 
} 

現在,顯然,上述代碼中沒有任何工作,並且我在解決方法時遇到了一些問題。任何人都可以幫我嗎?

回答

0

如果您嘗試對單詞數進行計數並將其存儲爲映射,那麼當添加新單詞時,嘗試將值1設置爲非0(單詞至少存在一次)。

爲了更新檢查映射是否包含鍵的值,然後再以增加的值重新放置它。舊值將被替換。

試試這個

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} 
+0

三江源這麼多先生,這解決了我的問題。 – Triple777er

2

您的地圖應該是Map<String, Integer>:對於每個單詞,您都有一個存儲單詞出現次數的整數。

爲了得到一個字的出現次數:Integer numberOfOccurrences = map.get(word);

要測試這個詞在地圖:if (numberOfOccurrences != null)

爲了增加出現的次數:numberOfOccurrences++;

要存儲新地圖上的值:map.put(word, numberOfOccurrences);

沒有理由迭代地圖。您逐字讀取您的文件,並使用上述來增加每個單詞的出現次數。

+0

三江源非常多,我很欣賞你的幫助 – Triple777er

相關問題