Skip to content

Basics/read_write_file/exercise/poem #263

Open
@FaryalBhatti

Description

@FaryalBhatti

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions