Jan-19-2019, 02:59 PM
A class example,here is not
Now could this be changed in the function version to,but this is a class example how to do it
filename
or most_common
Hard-coded in code.Now could this be changed in the function version to,but this is a class example how to do it
from collections import Counter import re class WordCounter: def file_read(self, file_name): with open(file_name) as f: self.text = f.read().lower() @property def word_count(self): wordlist = self.text.split() print(f"A total of {len(wordlist)} words can be found inside this text file.") def rank_words(self, count_amount: int) -> int: '''Count most common word in a text''' words = re.findall('\w+', self.text) top_10 = Counter(words).most_common(count_amount) for word,count in top_10: print(f'{word:<4} {"-->":^4} {count:>4}')Use class:
>>> text = WordCounter() >>> text.file_read('Alice.txt') >>> text.word_count A total of 29465 words can be found inside this text file. >>> text.rank_words(5) the --> 1818 and --> 940 to --> 809 a --> 690 of --> 631