我应该使用python 3.4使用NLTK(情绪分析)分析莎士比亚文本。但我收到此错误消息:
**Traceback (most recent call last):
File "C:\Users\HAMIMOUNE\AppData\Roaming\nltk_data\shakespeare.py", line 8, in <module>
[ line.split('\t') for line in open("AFINN-96.txt") ]))
TypeError: <lambda>() missing 1 required positional argument: 'v'**
这是我的代码:
from nltk.corpus import shakespeare
from collections import defaultdict
import json
hamlet = shakespeare.xml('hamlet.xml')
speeches = hamlet.findall('.//SPEECH')
prevSpeaker = speeches[0].find('SPEAKER').text
afinn = dict(map(lambda k,v: (k,int(v)),
[ line.split('\t') for line in open("AFINN-96.txt") ]))
dict = defaultdict(lambda: defaultdict(lambda: 0))
for speech in speeches:
speaker = speech.find('SPEAKER').text
lines = "\n".join(line.text for line in speech.findall('LINE') if line.text is not None)
sentiment = sum(map(lambda word: afinn.get(word, 0), lines.lower().split()))
dict[speaker][prevSpeaker] += sentiment
prevSpeaker = speaker
print(json.dumps(dict, sort_keys=True, indent=4))
答案 0 :(得分:2)
map
使用参数调用函数(在本例中为字符串列表)。您需要调整lambda
以获取参数:
afinn = dict(map(lambda item: (item[0], int(item[1])),
[ line.split('\t') for line in open("AFINN-96.txt") ]))
替代使用dict-comprehension:
afinn = {k: int(v) for k, v in
[line.split('\t') for line in open("AFINN-96.txt")]}
顺便说一句,不要使用dict
作为变量名。覆盖它会阻止您使用内置函数/类型dict
。