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

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

python 中的內置函數輸入失敗

python 中的內置函數輸入失敗

侃侃無極 2023-10-31 14:53:16
我試圖返回一個由每個關鍵字以及每個關鍵字及其同義詞在每個文檔中出現的次數組成的元組列表。當輸入只是一個字符串(例如“happy”)時,我沒有問題,但是當我嘗試更多輸入(例如“happy”和“sad”)時,代碼只打印最后一個字符串的輸出(“sad”) )這是我的代碼:class Entry :    def __init__(self, input_word, input_synonyms) :        self.word = input_word        self.synonyms = input_synonymse1 = Entry("sad", ["unhappy", "upset"])e2 = Entry("happy", ["cheerful", "joyful"])Thesaurus = [e1, e2]doc1 = ["the", "man", "is", "sad", "very", "sad", "and", "unhappy", "and", "upset"]doc2 = ["the", "boy", "is", "happy", "cheerful", "and", "joyful"]Corpus = [doc1, doc2]def search(keyword) :    all_words = [keyword]    for entry in Thesaurus:        if entry.word == keyword:            for word in entry.synonyms:                all_words.append(word)    store = []    for search_word in all_words:        count = 0        for document in Corpus:            for word in document:                if search_word == word:                    count = count + 1        store.append([search_word, count])    return storeinput_ = "happy" and "sad"output = search(input_)print(output)控制臺輸出:[['sad', 2], ['unhappy', 1], ['upset', 1]]預期輸出:[['happy', 1], ['cheerful', 1], ['joyful', 1], ['sad', 2], ['unhappy', 1], ['upset', 1]]有什么辦法可以解決這個問題嗎?
查看完整描述

1 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

接下來的代碼運行良好:


class Entry :

    def __init__(self, input_word, input_synonyms) :

        self.word = input_word

        self.synonyms = input_synonyms


e1 = Entry("sad", ["unhappy", "upset"])

e2 = Entry("happy", ["cheerful", "joyful"])

Thesaurus = [e1, e2]

doc1 = ["the", "man", "is", "sad", "very", "sad", "and", "unhappy", "and", "upset"]

doc2 = ["the", "boy", "is", "happy", "cheerful", "and", "joyful"]

Corpus = [doc1, doc2]


def search(keyword) :

    all_words = ["happy", "cheerful", "joyful", "sad", "unhappy", "upset"]

    for entry in Thesaurus:

        if entry.word == keyword:

            for word in entry.synonyms:

                all_words.append(word)

    store = []

    for search_word in all_words:

        count = 0

        for document in Corpus:

            for word in document:

                if search_word == word:

                    count = count + 1

        store.append([search_word, count])

    return store


input_ = ("happy", "cheerful", "joyful", "sad", "unhappy", "upset")

output = search(input_)

print(output)


控制臺輸出:


[['happy', 1], ['cheerful', 1], ['joyful', 1], ['sad', 2], ['unhappy', 1], ['upset', 1]]



查看完整回答
反對 回復 2023-10-31
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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