Created
November 11, 2019 12:55
-
-
Save yesnik/4067612645632e7e389df44fdaa01b8a to your computer and use it in GitHub Desktop.
Python. Display the most frequent words in the text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Free e-books: http://www.gutenberg.org/ | |
file_name = 'dickens_charles_great_expectations.txt' | |
with open(file_name) as file_object: | |
words_count = {} | |
for line in file_object.readlines(): | |
line_words = line.split(' ') | |
for word_raw in line_words: | |
word = word_raw.strip().lower() | |
if not word: | |
continue | |
if word in words_count: | |
words_count[word] += 1 | |
else: | |
words_count[word] = 0 | |
def dict_val(x): | |
return x[1] | |
words_sorted = sorted(words_count.items(), key=dict_val, reverse=True) | |
for word, count in words_sorted[:50]: | |
print(word + ' ' + str(count)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment