为了账号安全,请及时绑定邮箱和手机立即绑定

函数中的聚合无法正常工作

函数中的聚合无法正常工作

慕村225694 2023-08-08 10:22:30
你好,我有一个 python 函数正在工作,但没有按照我期望的方式工作,我不确定我的代码在哪里。def preprocess(text):    case = truecase.get_true_case(text)    doc = nlp(case)    return docdef summarize_texts(texts):    actions = {}    entities = {}    for item in texts:        doc = preprocess(item)        for token in doc:            if token.pos_ == "VERB":                actions[str.lower(token.text)] = actions.get(token.text, 0) +1        for token in doc.ents:            entities[token.label_] = [token.text]            if token.text not in entities[token.label_]:                entities[token.label_].append(token.text)    return {        'actions': actions,        'entities': entities    }当我调用句子列表的函数时,这是我得到的输出:docs = [    "Play something by Billie Holiday, and play again",    "Set a timer for five minutes",    "Play it again, Sam"]summarize_texts(docs)output: {'actions': {'play': 1, 'set': 1}, 'entities': {'PERSON': ['Sam'], 'TIME': ['five minutes']}}它正在查找操作键和实体键,但我遇到两个问题。它没有计算正确的动作它只存储每个实体的最后一个值。输出应该是:output: {'actions': {'play': 3, 'set': 1}, 'entities': {'PERSON': ['Billie','Sam'], 'TIME': ['five minutes']}}任何帮助都会很棒!我有一种感觉,这很简单,但太烧脑了,看不到它。
查看完整描述

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)

    


查看完整回答
反对 回复 2023-08-08
?
九州编程

TA贡献1785条经验 获得超4个赞

您在将令牌转换为小写方面不一致。分配给字典时使用小写版本,但调用时使用原始大小写actions.get()。因此,如果令牌具有混合大小写,则在调用 时将继续获取默认值actions.get(),并继续将其设置为 1。

actions[token.text.lower()] = actions.get(token.text.lower(), 0) +1


查看完整回答
反对 回复 2023-08-08
  • 2 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信