2 回答
![?](http://img1.sycdn.imooc.com/5458477f0001cabd02200220-100-100.jpg)
TA贡献1824条经验 获得超5个赞
您正在替换数据结构,而不仅仅是更新值。如果此时不存在,您只想创建一个新容器。
对于行动:
if token.pos_ == "VERB":
action_key = str.lower(token.text)
if action_key not in actions:
actions[action_key] = 0
actions[action_key] += 1
对于实体:
for token in doc.ents:
entity_key = token.label_
entity_value = token.text
if entity_key not in entities:
entities[entity_key] = []
if entity_value not in entities[entity_key]:
entities[entity_key].append(entity_value)
请注意,您可以使用defaultdict. 您还可以使用一组,而不是每次都检查列表中是否有重复项
actions = defaultdict(int)
entities = defaultdict(set)
...
if token.pos_ == "VERB":
actions[str.lower(token.text)] += 1
...
for token in doc.ents:
entities[token.label_].add(token.text)
![?](http://img1.sycdn.imooc.com/54584c910001b8d902200220-100-100.jpg)
TA贡献1785条经验 获得超4个赞
您在将令牌转换为小写方面不一致。分配给字典时使用小写版本,但调用时使用原始大小写actions.get()
。因此,如果令牌具有混合大小写,则在调用 时将继续获取默认值actions.get()
,并继续将其设置为 1。
actions[token.text.lower()] = actions.get(token.text.lower(), 0) +1
添加回答
举报