2016-12-15 34 views
-1

我想從文本文件中統計每個單詞並將單詞和計數作爲鍵值對附加到字典中。它引發了我這個錯誤:如果鍵不在wordDict中: TypeError:不可用類型:'list' 另外,我想知道.split()很好,因爲我的文本文件包含不同的標點符號。字典中的Python增量值

fileref = open(mypath + '/' + i, 'r') 
wordDict = {} 
for line in fileref.readlines(): 
    key = line.split() 
    if key not in wordDict: 
     wordDict[key] = 1 
    else: 
     wordDict[key] += 1 
+0

如果你想使用_additional_分隔符,你可以使用'line.replace(other,'')'在'split'之前。 – MSeifert

回答

2
from collections import Counter 
text = '''I am trying to count every word from text files and appending the word and count to a dictionary as the key-value pairs. It throws me this error: if key not in wordDict: TypeError: unhashable type: 'list' Also, I am wondering of .split() is good because my text files contain different punctuation marks. Thanks ahead for those who help!''' 

split_text = text.split() 
counter = Counter(split_text) 
print(counter) 

出來:

Counter({'count': 2, 'and': 2, 'text': 2, 'to': 2, 'I': 2, 'files': 2, 'word': 2, 'am': 2, 'the': 2, 'dictionary': 1, 'a': 1, 'not': 1, 'in': 1, 'ahead': 1, 'me': 1, 'trying': 1, 'every': 1, '.split()': 1, 'type:': 1, 'my': 1, 'punctuation': 1, 'is': 1, 'key': 1, 'error:': 1, 'help!': 1, 'those': 1, 'different': 1, 'throws': 1, 'TypeError:': 1, 'contain': 1, 'wordDict:': 1, 'appending': 1, 'if': 1, 'It': 1, 'Also,': 1, 'unhashable': 1, 'from': 1, 'because': 1, 'marks.': 1, 'pairs.': 1, 'this': 1, 'key-value': 1, 'wondering': 1, 'Thanks': 1, 'of': 1, 'good': 1, "'list'": 1, 'for': 1, 'who': 1, 'as': 1}) 
+0

這個例子可以用多行示例更好,str.splitlines()可以用於此。 :) – Copperfield

+0

@科波菲爾感謝提示 –

0

key是列表,你想看看一個列表是一本字典,相當於看它是否是關鍵之一。字典鍵canot是列表,因此「不可互換類型」錯誤。

1

key是在當前行中找到的空格分隔的單詞列表。您也需要遍歷該列表。

for line in fileref: 
    keys = line.split() 
    for key in keys: 
     if key not in wordDict: 
      wordDict[key] = 1 
     else: 
      wordDict[key] += 1 

這可以通過使用setdefault方法或從collections模塊defaultdict要麼相當清理;兩者都允許您避免通過自動添加具有初始值的密鑰來明確檢查密鑰(如果密鑰尚未在dict中)。

for key in keys: 
    wordDict.setdefault(key, 0) += 1 

from collections import defaultdict 
wordDict = defaultdict(int) # Default to 0, since int() == 0 

... 

    for key in keys: 
     wordDict[key] += 1 
0

str.split回報的話

>>> "hello world".split() 
['hello', 'world'] 
>>> 

和列表或任何其他可變對象不能用作字典的一個鍵,列表,這就是爲什麼你得到錯誤TypeError: unhashable type: 'list'

您需要遍歷它包括的每一個,也是推薦的方式與file工作與with statement

wordDict = {} 
with open(mypath + '/' + i, 'r') as fileref: 
    for line in fileref: 
     for word in line.split(): 
      if word not in wordDict: 
       wordDict[word] = 1 
      else: 
       wordDict[word] += 1 

上述可以通過使用Counter縮短和appropriate通話到它

from collections import Counter 

with open(mypath + '/' + i, 'r') as fileref:  
    wordDict = Counter(word for line in fileref for word in line.split()) 
+0

工作得很好,謝謝! – Yolanda