2017-11-07 12 views
0

次のコードは、エラーを与える:更新Pythonで辞書:「STR」オブジェクトアイテムの割り当てをサポートしていない

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 

エラーコードの最後の行に起因しています。

参考として、私は、2つのテキストファイルであるポジティブとネガティブから単語のハッシュテーブルを構築しようとしています。

最初にハッシュコードを取得するために単語をハッシュし、次にハッシュコードをキーとして適切な辞書に単語を格納しようとします。

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(' ') 
+0

ようこそStackOverflow。ヘルプドキュメントの投稿ガイドラインを読み、それに従ってください。 [最小、完全で検証可能な例](http://stackoverflow.com/help/mcve)がここに適用されます。 MCVEコードを投稿して問題を正確に記述するまでは、効果的にお手伝いすることはできません。 投稿したコードをテキストファイルに貼り付け、説明した問題を再現できるはずです。 – Prune

+2

辞書の名前を変更しようとしましたか?最初の一見から、このバグを引き起こしているかもしれないファイル名と辞書の名前が同じであるように見えます。 – TGWaffles

+3

'__init __()'の中で、 'positives'は辞書ではありません。メソッドのパラメータです。 – jasonharper

答えて

0

さんは名前がpositiveである(ただし、次にくるものが、同様negativesために保持する変数を考えてみましょう。

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

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

で(静的)変数positives = {}は-local __init__とは何の関係もないことに注意してください同じ名前の変数は、__init__(self, positives, ...の中の1つを意味します。

__init__の範囲外の最初のものを使用する場合は、だけがメソッド__init__の引数を参照しているため、があります。

あなたはOOPに精通していないようですので、あなたがそれらの二つの変数に同じ名前を持つことは、あなたの問題の理由ではない場合でも、混乱(そのタイプのを避けるために、これらの変数の1の名前を変更することがあり逆にあなたの質問の下のコメントにあるものを読むことができます)。同じ名前の辞書を保つのをみましょう、とは逆で、のは__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への値は 'str' objectです。

+0

まだOOPを完全に理解しているとは思えませんが、私は提案された変更を加えて動作させています!私の質問に答える時間をとってくれてありがとう。 – kevin

関連する問題