0% found this document useful (0 votes)
13 views2 pages

Implement Word Count

Uploaded by

ailurophileas24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Implement Word Count

Uploaded by

ailurophileas24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

Implement word count / frequency programs


import string

def word_count(file_path):

# Initialize an empty dictionary to store word counts

word_counts = {}

try:

# Open the file in read mode

with open(file_path, 'r') as file:

# Read the entire content of the file

text = file.read()

# Remove punctuation and convert text to lowercase

text = text.translate(str.maketrans('', '', string.punctuation)).lower()

# Split the text into individual words

words = text.split()

# Count the frequency of each word

for word in words:

if word in word_counts:

word_counts[word] += 1

else:

word_counts[word] = 1

return word_counts

except FileNotFoundError:

print(f"Error: The file at {file_path} was not found.")

return None
# Example usage

file_path = 'example.txt' # Replace this with the path to your text file

word_counts = word_count(file_path)

# Display the word counts if the dictionary is populated

if word_counts is not None:

for word, count in word_counts.items():

print(f"{word}: {count}")

OUTPUT

You might also like