2 回答

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)

TA貢獻1785條經驗 獲得超4個贊
您在將令牌轉換為小寫方面不一致。分配給字典時使用小寫版本,但調用時使用原始大小寫actions.get()
。因此,如果令牌具有混合大小寫,則在調用 時將繼續獲取默認值actions.get()
,并繼續將其設置為 1。
actions[token.text.lower()] = actions.get(token.text.lower(), 0) +1
添加回答
舉報