Итак, я написал код, который определяет 4 наиболее распространенных слова в текстовом файле, а затем находит все слова, встречающиеся на 2% и более. Мой код прекрасно работает до сих пор. Но я должен превратить циклы for в списки.
Пока я пробовал:
percent_list = [word, freq in word_counts.most_common(total) if ((freq/total)*100) >= 2.0]
Для второго цикла for (см. Весь код ниже.) Но это не работает. Это кажется немного длинным для понимания списка, потому что все онлайн кажутся намного короче.
Вот и вся программа. Всего два цикла for.
from collections import Counter
from operator import itemgetter
STOP = ["the", "and", "in", "to", "a", "of", "at", "it", "but", "its","it's", "that", "was", "with", "as", "are", "i","this", "for", "if"]
word_counts = Counter()
with open("file.txt") as f:
for token in f.read().split():
if token.lower() not in STOP:
word_counts[token.lower()] += 1
print( word_counts.most_common(4), ":")
total = sum(word_counts.values())
print("\nWords that occur for 2% or more are: ")
for word, freq in word_counts.most_common(total):
if ((freq/total)*100) >= 2.0:
print("\n {} ".format(word))