我正在设法把所有的单词和它的标记都记在字典里。但是,我一直收到一个键错误,我不明白为什么。在
sent = [[('Merger', 'NOUN'), ('proposed', 'VERB')], [('Wards', 'NOUN'), ('protected', 'VERB')]]
dicts = {}
for x in sent:
for y in x:
if y[0] in dicts.keys():
dicts[y[0]][y[1]] = 1
else:
dicts[y[0]][y[1]] += 1
错误:
^{pr2}$
Tags:
你把条件句弄错了。您需要先检查字典中是否存在该键,如果不存在,则创建该键。那么,你的巢穴太深了。您只需要
dicts[y[0]]
有一个简单的修复方法:在}。在
in dicts.keys()
之前添加not
,然后去掉{全部:
您还应该考虑查看^{} 和{a2}:
一个
defaultdict
将自动填充一个默认值,Counter
是一个专门用于计数的dict
:如果要跳过
^{pr2}$Counter
,只需使用一个helper函数,该函数返回一个defaultdict(int)
,并且不带任何参数:相关问题 更多 >
编程相关推荐