Создание списка предметов, каждому из которых присвоено значение - PullRequest
0 голосов
/ 11 января 2019

Я работаю над методом в Python, который подсчитывает, сколько раз слово используется во входном наборе (естественный язык), и я надеюсь, в следующем порядке:

  • Создать список слов (исключая общие слова, такие как 'I', 'you', 'a')

  • Поместите их в список

  • Назначьте им значение x (количество использованных раз)

  • Сортировать их по x

  • Вернуть отсортированный список

Пример:

Введите:

"one two two two three three three"

Выход:

["three", "two", "one"]

Проблема в том, что я не знаю, как создавать списки, в которых вы можете присваивать значения элементам.

Ответы [ 2 ]

0 голосов
/ 11 января 2019

Я обновил свой ответ, потому что он должен быть короче.

Вы можете получить 500 самых распространенных слов по этой ссылке

input_text = list('In the End, we will remember not the words of our enemies, but the silence of our friends.'.split())

stop_words = ['the', 'of', 'we', 'will', 'our', 'but', 'in']

removed_special_characters = ["".join(list(filter(str.isalnum, line.lower()))) for line in input_text]

non_stop_words = ([item for item in removed_special_characters if item not in stop_words])

print (non_stop_words)

# OUTPUT
#####################################################################
['end', 'remember', 'not', 'words', 'enemies', 'silence', 'friends']

Этот код дает вам частоту non_stop_words.

input_text = list('In the End, we will remember not the words of our enemies, but the silence of our friends.'.split())

stop_words = ['the', 'of', 'we', 'will', 'our', 'but', 'in']

removed_special_characters = ["".join(list(filter(str.isalnum, line.lower()))) for line in input_text]

non_stop_words = common_words_identified.update((Counter(([item for item in removed_special_characters if item not in stop_words])).most_common()))

sorted_by_word_occurrence = sorted(common_words_identified.items(), key=lambda kv: kv[1])

print (sorted_by_word_occurrence)

# OUTPUT
#####################################################################
[('end', 1), ('remember', 1), ('not', 1), ('words', 1), ('enemies', 1), ('silence', 1), ('friends', 1)]
0 голосов
/ 11 января 2019

Я не могу помочь вам со стоп-словами, так как я не знаю, какой метод вы хотите использовать, но для подсчета вы можете использовать collections.Counter:

from collections import Counter

example = "one two two two three three three"

count = Counter(example.split())

print(count.most_common())
# [('two', 3), ('three', 3), ('one', 1)]

Это даже связывает в счет для вас, но если вы не хотите:

print([tup[0] for tup in count.most_common()])
# ['two', 'three', 'one']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...