Friday, 6 May 2011

Python program to find repeated occurrence of words in a file and print them.

hi,

i made a program to find repeated occurrence of words in a file and print them.

the code is,

f1 = open('words1.txt')

file1lines = f1.readlines()
if len(file1lines) != 0 :
    uniquewords = set(word for line in file1lines for word in line.split(" "))
    wordlist = list(word for line in file1lines for word in line.split(" "))
    for words in uniquewords:
        print words.rstrip('\n')," : ",wordlist.count(words)," occurence"

f1.close

i/p:

(word1.txt)

hello therer
this is a text string
actually really
sundelly peruchally    
this is another string
this is a text string

o/p:

[parthi@localhost pyth files]$ python wordtimes.py
a  :  2  occurence
string  :  3  occurence
therer  :  1  occurence
really  :  1  occurence
this  :  3  occurence
text  :  2  occurence
is  :  3  occurence
actually  :  1  occurence
sundelly  :  1  occurence
another  :  1  occurence
peruchally     :  1  occurence
hello  :  1  occurence


No comments:

Post a Comment