In: Computer Science
how to count the word of occurance in the text file
example input text file : "test1.txt
hello : 1
good : 1
morning: 1
how : 1
are : 2
you : 2
good : 1
example output text file : "test2.txt"
1 : 4
2 : 2
3 : 0
4 : 0
5 : 0
Python Program:
#***********************************************
# EXTRACT DIGIT FROM FILE
#***********************************************
# Opening file in reading mode
file = open('test1.txt', 'r')
# Reading from the file and store it in 'content' variable
content = file.readlines()
# Variable for storing the numbers
numList = []
# Iterating through the contents of the file
for line in content:
# traverse in each line
for i in line:
# Check numeric or digit in line
if i.isdigit() == True:
numList.append(int(i))
#***********************************************
# FREQUENCY OF NUMBER
#***********************************************
# Calculate Frequency of each number
freq = {}
for items in numList:
freq[items] = numList.count(items)
# Print Frequnecy Table
print("\n***************************")
print("Number | Frequency")
print("***************************")
for key, value in freq.items():
print ("% s : % d"%(key, value))
print("***************************")
Text - File => test1.txt
hello : 1
good : 1
morning : 1
how : 1
are : 2
you : 2
good : 1
Output:
Thumbs Up Please !!!