word counter
import string
def count_words(text):
# Remove punctuation and convert to lowercase
text = text.lower()
text = text.translate(str.maketrans("", "", string.punctuation))
# Split the text into words
words = text.split()
# Count the frequency of each word
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
def read_file(file_path):
with open(file_path, 'r') as file:
return file.read()
# Example usage
file_path = 'example.txt' # Replace with your file path
text = read_file(file_path)
word_count = count_words(text)
# Print the total number of words and the frequency of each word
total_words = sum(word_count.values())
print(f"The total number of words is: {total_words}")
print("Word frequencies:")
for word, count in word_count.items():
print(f"{word}: {count}")
Comments
Post a Comment