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

Basics/read_write_file/exercise/poem #263

Open
FaryalBhatti opened this issue Apr 20, 2024 · 0 comments
Open

Basics/read_write_file/exercise/poem #263

FaryalBhatti opened this issue Apr 20, 2024 · 0 comments

Comments

@FaryalBhatti
Copy link

The issue in your code likely arises from case sensitivity when counting words. If the same word appears in different cases (e.g., "Hello" and "hello"), they will be treated as separate words in the word_stats dictionary, leading to inaccurate word counts. By using cleaned_word.lower() before updating the dictionary, all words are standardized to lowercase. This ensures uniform representation of words regardless of their original case, thus preventing duplication and providing accurate word counts.

following is the correct code:
word_stats = {}
with open("D:/data-science-roadmap-2024/poem.txt","r") as f:
for line in f:
words=line.split()
for word in words:
# Remove any non-alphanumeric characters from the word
# This can help in cleaning the words and handling punctuation
cleaned_word = ''.join(filter(str.isalnum, word))
# Convert the word to lowercase for case-insensitive counting
cleaned_word = cleaned_word.lower()
if word in word_stats:
word_stats[word]+=1
else:
word_stats[word] = 1

print(word_stats)

word_occurances = list(word_stats.values())
max_count = max(word_occurances)
print("Max occurances of any word is:",max_count)

print("Words with max occurances are: ")
for word, count in word_stats.items():
if count==max_count:
print(word)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant