Exercise 60

Write a Python program that allows you to count the frequency of repetition of each word found in a given file.

Solution

# opening the myfile.txt in read mod
file = open("myfile.txt" , 'r')

# obtaining the myfile.txt content
content = file.read()

# closing the txt file
file.close()

# converting the content on python list
L = content.split()

# creation of an empty list which will contain unique elements
uniqueList = []

# browsing through list items
for word in L:
if word not in uniqueList:
uniqueList.append(word)
print("Frequency of : " + word + " : " + str(L.count(word)))

Output example

If the content of myfile.txt is 
content = 'Python is programming language. Python is object oriented programming language.'  
the output will be:
Frequency of : Python : 2
Frequency of : is : 2
Frequency of : programming : 2
Frequency of : language. : 2
Frequency of : object : 1
Frequency of : oriented : 1

Younes Derfoufi
my-courses.net

Leave a Reply