Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update exercise_1_poem.py #246

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion Basics/Exercise/13_read_write_files/exercise_1_poem.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,24 @@
print("Words with max occurances are: ")
for word, count in word_stats.items():
if count==max_count:
print(word)
print(word)
#I tried the above code and found the answer to be as follows:
'''Max occurances of any word is: 8
Words with max occurances are:
I
the'''
#However, when I tried solving the problem on my own, it resulted in the following output at the end:
'''The word with maximum occurrence is 'and' with count 9'''
word_counts={}
with open("C://Users//Tahir//Desktop//poem.txt","r+") as p:
for line in p:
tokens=line.lower().split(' ') #to ensure 'The' and 'the' are counted as same words. At the same time tokenize each line.
for word in tokens:
word= word.strip(',.!?;:') #remove punctuation so that 'word,' and 'word' are counted same.
if word in word_counts:
word_counts[word]+=1
else:
word_counts[word]=1
print(word_counts)
max_word=max(word_counts, key=word_counts.get) #key argument tells max() to operate on the word counts instead of keys which are just words here sorted in lexicographical order.
print(f"The word with maximum occurrence is '{max_word}' with count {word_counts[max_word]}")