gpt4 book ai didi

python - python中的Lambda参数函数

转载 作者:行者123 更新时间:2023-12-01 04:56:43 26 4
gpt4 key购买 nike

我应该使用 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))

最佳答案

map使用参数(在本例中为字符串列表)调用该函数。您需要调整 lambda 来获取参数:

afinn = dict(map(lambda item: (item[0], int(item[1])), 
[ line.split('\t') for line in open("AFINN-96.txt") ]))

使用字典理解的替代方法:

afinn = {k: int(v) for k, v in
[line.split('\t') for line in open("AFINN-96.txt")]}

顺便说一句,不要使用 dict 作为变量名。覆盖它会阻止您使用内置函数/类型 dict .

关于python - python中的Lambda参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com