.

Saturday, August 15, 2015

Python program to find number of times each word is in the .txt file OR that finds most frequent word in a .txt file.

__author__ = 'kamal'
 import re
from collections import Counter
f=open('C:\Python27\myfile.txt', 'r')
passage = f.read()
words = re.findall(r'\w+', passage)
cap_words = [word.upper() for word in words]
# Converting to uppercase so that 'Is' & 'is' like words  should be considered as same words
word_counts = Counter(cap_words)
print(word_counts)











Output------------------------------------------------

Counter({'USED': 2, 'IN': 2, 'THE': 2, 'FREQUENT': 2, 'TO': 1, 'WORD': 1, 'MOST': 1, 'THIS': 1, 'OF': 1, 'IS': 1, 'NUMBER': 1, 'LEAST': 1, 'TIMES': 1, 'ALSO': 1, 'PROGRAM': 1, 'MANNER': 1, 'FILE': 1, 'EACH': 1, 'COUNTS': 1, 'SORTED': 1, 'HELLO': 1})

Process finished with exit code 0

No comments :

Post a Comment

There was an error in this gadget