Thursday, 5 May 2011

Python program to print number of occurrences of lines in a file from another file

hi,

Today i made a python program to print number of occurrences of lines in a file from another file.

the code is,

f1 = open('words.txt')
f2 = open('words1.txt')

file1lines = f1.readlines()
file2lines = f2.readlines()
if len(file1lines) != 0 | len(file2lines) != 0:
    for everyline in file1lines:
        print file2lines.count(everyline)," occurrences :",everyline.rstrip('\n')

f1.close
f2.close

snap - explanation : reading all lines from two files - storing lines in list - comparing with for loop - then printing the line and occurrence.

i/p:

(word.txt)

this is a text string
this is another string

(word1.txt)

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

o/p:

2 occurrence : this is a text string
1 occurrence : this is another string


No comments:

Post a Comment