' STR' object不支持python中的项目赋值错误

时间:2015-09-24 18:05:16

标签: python string dictionary

以下代码:

words={}
words_with_meaning_list=[]
words_without_meaning_list=[]
words_file=open('words/word_meaning.txt','a+')
words_with_meaning_file=open('words/words_with_meaning.txt','a+')
words_without_meaning_file=open('words/words_without_meaning.txt','a+')

words_with_meaning_list=words_with_meaning_file.readlines()
words_without_meaning_list=words_without_meaning_file.readlines()
words=words_file.read()

def add_word(word,meaning='none'):
    words[word]=meaning
    if(meaning=='none'):
        words_without_meaning_list.append(word)
    else:
        words_with_meaning_list.append(word)    

def input_machine(repeat):
    if(repeat=='y' or repeat=='Y'):
        the_word=input('Enter the word you want to add:')
        choice=input('If you know the meaning of the word press y or Y:')

        if(choice=='y' or choice=='Y'):
            the_meaning=input('Enter the meaning:')
            add_word(the_word,the_meaning)
        else:       
            add_word(the_word)
    else:
        s1='\n'.join(words_with_meaning_list)
        s2='\n'.join(words_without_meaning_list)
        s3='\n'.join(words)
        print (s1)
        print (s2)
        print (s3)
        words_with_meaning_file.write(s1)
        words_without_meaning_file.write(s2)
        words_file.write(s3)    

input_machine('y')

repeat=input('Do you want to continue adding meaning. press y or Y:')

while(repeat=='y'):
    input_machine(repeat)
    repeat=input('Do you want to continue adding meaning. press y or Y:')


print (words)   

给出以下错误 TypeError:' str'对象不支持项目分配。

错误在'单词[word] =含义'。我无法理解这个错误。单词是字典类型,我们可以用上面的格式添加新的键和值,然后我为什么会收到错误。请帮帮我。

1 个答案:

答案 0 :(得分:3)

您正在更改变量words。你从

开始
words={}

然后几行

words=words_file.read()

在第二行之后,words现在是str,所以你无法做到

words[word]=meaning