次のコードは、エラーを与える:更新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(' ')
ようこそStackOverflow。ヘルプドキュメントの投稿ガイドラインを読み、それに従ってください。 [最小、完全で検証可能な例](http://stackoverflow.com/help/mcve)がここに適用されます。 MCVEコードを投稿して問題を正確に記述するまでは、効果的にお手伝いすることはできません。 投稿したコードをテキストファイルに貼り付け、説明した問題を再現できるはずです。 – Prune
辞書の名前を変更しようとしましたか?最初の一見から、このバグを引き起こしているかもしれないファイル名と辞書の名前が同じであるように見えます。 – TGWaffles
'__init __()'の中で、 'positives'は辞書ではありません。メソッドのパラメータです。 – jasonharper