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

你好,我有一个 python 函数正在工作,但没有按照我期望的方式工作,我不确定我的代码在哪里。


def preprocess(text):

    case = truecase.get_true_case(text)

    doc = nlp(case)

    return doc


def 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']}}

任何帮助都会很棒!我有一种感觉,这很简单,但太烧脑了,看不到它。


慕村225694
浏览 105回答 2
2回答

沧海一幻觉

您正在替换数据结构,而不仅仅是更新值。如果此时不存在,您只想创建一个新容器。对于行动: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)    

九州编程

您在将令牌转换为小写方面不一致。分配给字典时使用小写版本,但调用时使用原始大小写actions.get()。因此,如果令牌具有混合大小写,则在调用 时将继续获取默认值actions.get(),并继续将其设置为 1。actions[token.text.lower()] = actions.get(token.text.lower(), 0) +1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python