Home » All Blogs » Python » Python assignments » M.Sc Computer Application » M.Sc Python Programming Assignment 26
M.Sc Python Programming Assignments
Assignment 26
Question:
Write a Python program to count the frequency of words in a file
Code:
def count_word_frequency(file_name):
word_frequency = {}
with open(file_name, 'r') as file:
for line in file:
words = line.strip().split()
for word in words:
if word in word_frequency:
word_frequency[word] += 1
else:
word_frequency[word] = 1
return word_frequency
# Example usage
file_name = input("Enter the file name: ")
word_frequency = count_word_frequency(file_name)
print("Word frequency in the file:")
for word, frequency in word_frequency.items():
print(f"{word}: {frequency}")
Output:
Word frequency in the file:
lucifer: 1