在python中更新字典:' str'对象不支持项目分配

时间:2017-11-07 19:12:21

标签: python dictionary

以下代码给出错误:

File "/home/ubuntu/workspace/pset6/sentiments/analyzer.py", line 20, in __init__
    positives[h] = line.strip(' ') # store word and hash code in dictionary
TypeError: 'str' object does not support item assignment

错误是由代码中的最后一行引起的。

作为参考,我正在尝试从正面和底面构建一个哈希表,这是两个文本文件。

首先我对该单词进行散列以获取哈希码,然后我尝试将该单词存储在相应的字典中,并将哈希码作为键。

import nltk

class Analyzer():
    """Implements sentiment analysis."""

    # create two new dictionaries to store positive and negative words in memory
    positives = {}
    negatives = {}

    def __init__(self, positives, negatives):
        """Initialize Analyzer."""

        # open positive-words.txt and read line by line, hashing each line and storing the hash and word in the appropriate dictionary
        with open(positives, "r") as lines:
            for line in lines:
                if line.startswith(';'): # ignore comments at top of text file
                    continue
                else:
                    h = hash(line.strip(' ')) # hash word using built in python hash function, removing any spaces
                    positives[h] = line.strip(' ') # store word and hash code in dictionary

        # open negative-words.txt and read line by line, hashing each line and storing the hash and word in the appropriate dictionary
        with open(negatives, "r") as lines:
            for line in lines:
                if line.startswith(';'):
                    continue
                else:
                    h = hash(line.strip(' '))
                    negatives[h] = line.strip(' ')

1 个答案:

答案 0 :(得分:0)

让我们考虑名称为positive的变量(但negatives的内容也适用。注意在

# ...
positives = {}
negatives = {}

def __init__(self, positives, negatives):
    """Initialize Analyzer."""
    # ...

(静态)变量positives = {}__init__ - 同名的局部变量无关,我的意思是__init__(self, positives, ...中的变量。

如果要使用__init__范围之外的第一个,则必须键入self.positives,因为positives单独指的是方法{{1}的参数}}

由于您似乎不熟悉OOP,您可以重命名其中一个变量以避免这种混淆(即使这两个变量的名称相同 不是您的问题的原因 ,与您在问题下方的评论中可以阅读的内容相反。让我们保持字典的名称相同,相反,让我们重命名__init__的参数,使用代表它的名称,即文件名:

__init__

你明白我的观点吗?

当你想要实例化你的课时,我想你会做

#...

# create two new dictionaries to store positive and negative words in memory
positives = {}
negatives = {}

def __init__(self, fname_of_pos, fname_of_neg):
    """Initialize Analyzer."""

    # open positive-words.txt and read line by line, hashing each line and storing the hash and word in the appropriate dictionary
    with open(fname_of_pos, "r") as lines:
        for line in lines:
            if line.startswith(';'): # ignore comments at top of text file
                continue
            else:
                h = hash(line.strip(' ')) # hash word using built in python hash function, removing any spaces
                self.positives[h] = line.strip(' ') 
    #...

<小时/> 总而言之,如果您收到错误,那只是因为您试图为(重新命名的)变量>>> an_instance_of_analyser = Analyzer('positive-words.txt','negative-words.txt') 分配一个值fname_of_pos