#python-3.x
#python-3.x
Вопрос:
Допустим, у нас есть набор документов
corpus = [
'this is the first document',
'this document is the second document',
'and this is the third one',
'is this the first document',
]
Как найти количество уникальных терминов в каждом предложении?
Я использовал
count = dict(Counter(word for sentence in document for word in sentence.split()))
и результат, который я получил, был
{'this': 4, 'is': 4, 'the': 4, 'first': 2, 'document': 4, 'second': 1, 'and': 1, 'third': 1, 'one': 1}
Я ищу результат, в котором ключ «документ» имеет значение 3 вместо 4, потому что он встречается в 3 из 4 предложений.
Ответ №1:
Если вы хотите, чтобы слово учитывалось только один раз для каждого предложения, вы можете составить set
из слов в предложении перед подсчетом:
from collections import Counter
corpus = [
'this is the first document',
'this document is the second document',
'and this is the third one',
'is this the first document',
]
count = dict(Counter(word for sentence in corpus for word in set(sentence.split())))
count
будет:
{'first': 2,
'this': 4,
'document': 3,
'the': 4,
'is': 4,
'second': 1,
'third': 1,
'and': 1,
'one': 1}