Feb-17-2025, 02:36 AM
I'm working on a Python project where I need to read a text file, count the occurrences of each word, and then display the top 10 most common words. Here's what I have so far, but I'm struggling with optimizing it and handling punctuation properly. Any suggestions?
from collections import Counter def count_words(filename): with open(filename, 'r', encoding='utf-8') as file: words = file.read().lower().split() word_counts = Counter(words) return word_counts.most_common(10) filename = 'sample.txt' # Example file print(count_words(filename))Link Removed