Python:txt进入字典。Split()类型错误:不可损坏类型:“list”

2024-09-30 08:33:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始使用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()

^{pr2}$

但现在不行了。我得到:

dictionairy[word] = counter
TypeError: unhashable type: 'list'

有谁能给我解释一下为什么会发生这种情况,并给我一个提示,告诉我该怎么解决它?求你了,漂亮了吗?在


Tags: 答案in程序txt字典oslinecounter
1条回答
网友
1楼 · 发布于 2024-09-30 08:33:54

使用str.split()之后,您将得到一个拆分单词的列表,您需要遍历该列表并将其设置为字典。示例-

for line in fh:
    words = line.rstrip().split()
    for word in words:
        dictionairy[word] = counter
        counter += 1

相关问题 更多 >

    热门问题