You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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)
The text was updated successfully, but these errors were encountered:
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 usingcleaned_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)
The text was updated successfully, but these errors were encountered: