【问题标题】:Builtin function failing for input in python内置函数在python中输入失败
【发布时间】:2020-10-12 00:48:20
【问题描述】:

我正在尝试返回由每个关键字和每个关键字的出现次数及其在每个文档的同义词组成的元组列表。

当输入只是一个字符串(例如“happy”)时我没有问题,但是当我尝试更多输入(例如“happy”和“sad”)时,代码只会打印最后一个的输出( “悲伤”)

这是我的代码:

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 = [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 store

input_ = "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]]

有没有办法解决这个问题?

【问题讨论】:

  • "happy" and "sad" 计算结果为 "sad"。首先检查"happy" 的真值。因为它被认为是真的,所以 "sad" 被评估并成为表达式的值。您是否尝试构建tupletuple 的语法为 ("happy", "sad")

标签: python function tuples output


【解决方案1】:

考虑到@Tom Karzes 的评论,

下一个代码运行良好:

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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多