我目前被此Python练习所阻止。我想知道一个单词及其同义词在文档集中的出现。
[Entry是具有属性“ word”和“ synonyms”的类。
class Entry :
def __init__(self, input_word, input_synonyms) :
self.word = input_word
self.synonyms = input_synonyms
同义词库是条目列表
e1 = Entry("dog", ["doggie", "puppy"])
e2 = Entry("cat", ["kitty"])
Thesaurus = [e1, e2]
语料库是文档的列表,而每个文档是字符串的列表。
doc1 = ["this", "is", "a", "single”, “document"]
doc2 = ["this", "is", "another", "document"]
Corpus = [doc1, doc2]
我试图通过将计数存储在“ store”变量中来尝试,但是它总是返回0。我认为有些错误是因为我没有捕获正确的关键字,或者我没有正确存储“ count”。] >
这是我的代码:
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" output = search(input) print(output)
此刻我得到的是:
[['happy', 0]]
预期结果应该在这些行中:
[('happy', 16), ('glad', 2), ('pleased', 2), ('delighted', 2), ('joyous', 1)]
我目前被此Python练习所阻止。我想知道一个单词及其同义词在文档语料库中的出现。条目是具有“单词”和“同义词”属性的类。 ...
您的代码很好,但是,我发现了一些缩进问题并予以纠正。
这应该起作用: