【发布时间】:2018-06-04 09:07:31
【问题描述】:
我不擅长编程,只是为了好玩和在线获取代码示例。所以我决定我想做以下事情:
- 统计总字数
- 计算“whereby”字数
- 除以总字数的'whereby'计数
但是,我不断收到“不可散列的类型:“列表”。我认为这是因为我使用了 frequency_list 但我不明白我该怎么做。
错误回溯: 回溯(最近一次通话最后): 文件“C:\Users\user\AppData\Local\Programs\Python\Python36-32\whereby.py”,第 31 行,在 打印(整数(频率[字数])/字数) TypeError: unhashable type: 'list'
import re
import string
frequency = {}
wherebyity = {}
document_text = open('C:/Users/user/desktop/text.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall('whereby', text_string)
for word in match_pattern:
count = frequency.get(word, 0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print (words, frequency[words])
print (type(frequency))
print (type(frequency[words]))
print (frequency)
with open('C:/Users/user/desktop/text.txt', 'r') as f:
p = f.read() # p contains contents of entire file
# logic to compute word counts follows here...
words = p.split()
wordCount = len(words)
print ("The total word count is:", wordCount)
print (type(wordCount))
print(int(frequency[words])/wordCount)
【问题讨论】:
-
我们能看到错误痕迹吗?
-
Traceback(最近一次调用最后):文件“C:\Users\user\AppData\Local\Programs\Python\Python36-32\whereby.py”,第 31 行,在
中打印(int(frequency[words])/wordCount) TypeError: unhashable type: 'list' -
我怀疑 'words' 是一个列表,而不是关键字 - 您不能将列表用作 dict 关键字。在调试器中检查 'words' 并验证它是否是您所需要的。
标签: python