f-string can be used in all cases,then avoid rather ugly string like this.
Running
We don't want it run at import.
Use it like this:
The code run when import it,in almost all cases this not wanted.
print("A total of " + str(len(wordlist)) + " words can be found inside this text file.")To make the code work,and look into that function can take arguments.
# word_count.py from collections import Counter import re def word_count(text): wordlist = text.split() print(f"A total of {len(wordlist)} words can be found inside this text file.") def rank_words(text): words = re.findall('\w+', text) top_10 = Counter(words).most_common(10) for word,count in top_10: print(f'{word:<4} {"-->":^4} {count:>4}') def file_read(): with open('alice.txt') as f: text = f.read().lower() return text if __name__ == '__main__': text = file_read() word_count(text) rank_words(text)Can now give a demo on how
if __name__ == '__main__':
work.Running
word_count.py
script now.Output:A total of 29465 words can be found inside this text file.
the --> 1818
and --> 940
to --> 809
a --> 690
of --> 631
it --> 610
she --> 553
i --> 543
you --> 481
said --> 462
Now will import the script.>>> import word_count >>> # Nothing happensThis is what we want when import code as module.
We don't want it run at import.
Use it like this:
>>> import word_count >>> text = word_count.file_read() >>> word_count.word_count(text) A total of 29465 words can be found inside this text file. >>> word_count.rank_words(text) the --> 1818 and --> 940 to --> 809 a --> 690 of --> 631 it --> 610 she --> 553 i --> 543 you --> 481 said --> 462Now if remove
if __name__ == '__main__':
.The code run when import it,in almost all cases this not wanted.
>>> import word_count A total of 29465 words can be found inside this text file. the --> 1818 and --> 940 to --> 809 a --> 690 of --> 631 it --> 610 she --> 553 i --> 543 you --> 481 said --> 462