Как я могу вернуть элементы из списка с номером вхождения в документе? - PullRequest
0 голосов
/ 09 ноября 2019

В настоящее время я заблокирован этим упражнением на Python. Я хочу знать вхождение слова и его синонимов в совокупность документов.

Запись - это класс с атрибутами «слово» и «синонимы».

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

1 Ответ

1 голос
/ 09 ноября 2019

Ваш код в порядке, однако я нашел некоторые проблемы с отступами и исправил их.

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 = ["dog", "is", "a", "puppy", "and", "a", "puppy", "is", "doggie"]
doc2 = ["this", "is", "another", "document"]
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

inp = "dog"
output = search(inp)
print(output)

Возвращает следующее:

[['dog', 1], ['doggie', 1], ['puppy', 2]]
...