我刚开始使用Python,但在一个练习中遇到了一些问题。如果这个问题太“基本”了,我真的很抱歉,但我已经在谷歌上做了调查,没有找到任何简短而不太复杂的答案。现在练习:
“编写一个程序来读入单词文字.txt并将它们作为键存储在字典中。值是什么并不重要。然后,您可以使用in运算符作为检查字符串是否在字典中的快速方法。”
我试过了:
import os
os.chdir("/Users/MissOgra/Documents")
fname = input("File name: ")
if len(fname) < 1 : fname = "words.txt"
fh= open(fname)
counter = 0
dictionairy = dict()
for line in fh:
word = line.rstrip()
dictionairy[word] = counter
counter += 1
print(dictionairy)
但是,我不懂单词,而是句子。所以我想我可以这样使用split()
:
但现在不行了。我得到:
dictionairy[word] = counter
TypeError: unhashable type: 'list'
有谁能给我解释一下为什么会发生这种情况,并给我一个提示,告诉我该怎么解决它?求你了,漂亮了吗?在
使用
str.split()
之后,您将得到一个拆分单词的列表,您需要遍历该列表并将其设置为字典。示例-相关问题 更多 >
编程相关推荐