我试图将列表“lines”中的每个项目与字典“dic”进行比较,然后将lines中的项目添加到dic(如果不存在),或者将1添加到中的键值字典。
import string
def uniques():
file = open("test.txt", "r")
dic = {}
data = file.read().replace('\n', ' ')
strip = removePunctuation(data)
lines = strip.split(' ')
print(strip)
print(lines)
for item in lines:
#this produces an error of unhashable type: 'list'
if lines in dic:
dic[item] = dic[item] + 1
else:
print("else ran")
dic[item] = 1
for item in dic:
print(item, dic[item])
print("There are " + str(len(dic)) + " items in the dictionary")
def removePunctuation(text):
text = text.strip()
return text.rstrip(string.punctuation)
uniques()
最佳答案
它
if item in dic:
dic[item] = dic[item] + 1
而不是
if lines in dic:
dic[item] = dic[item] + 1
关于Python 字典和列表比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960121/