Jan-19-2019, 04:21 AM
Thank you @stullis for the clarification. I’ve moved lines 21 and 22 into my
For what it’s worth, here is the updated working script:
@snippsat: I like the polish and I appreciate the detailed explanation about how you need
main()
function. It runs beautifully as expected. I’ll keep in mind for next time to run all the required code in my program inside main()
and I’ll avoid using a return operation there as well.For what it’s worth, here is the updated working script:
from collections import Counter import re def word_count(text): wordlist = text.split() print("A total of " + str(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 main(): with open('Alice.txt') as f: text = f.read().lower() word_count(text) rank_words(text) if __name__ == '__main__': main() passAnd the output:
Output:$ python with_word_count.py
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
@snippsat: You are right that f-string formatting is more readable and more concise. It’s cleaner and less ugly. When I wrote that string concatenation line initially, I just used whatever was most obvious. On my lunch break tomorrow I’ll read a tutorial I found called “Python 3's f-Strings: An Improved String Formatting Syntax (Guide)” @snippsat: I like the polish and I appreciate the detailed explanation about how you need
if __name__ == '__main__':
if you are importing a script as a module in the interpreter on the fly. I’ve looked up if __name__ == '__main__':
on Google and there are many tutorials and guides. The most upvoted question and subsequent answers on SO explaining and describing this mechanism in Python I find to be overly confusing right now. I suppose once I learn more about classes and with more general experience with Python, the logic and syntax of if __name__ == '__main__':
will make more sense. @snippsat: Compared to Sackoverflow, your explanation is easier to understand because it's in the context of my script. Thank you.