亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

函數中的聚合無法正常工作

函數中的聚合無法正常工作

慕村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 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號