Halv a dozen Thigs I dont like about your code:
1.)
file = ....
file is a keyword in python, but you use it as a variable
2.)
while infile: ....
infile is a file object, so it will always be true, you may as well write
while 1: ...
3.)
You test for an occurance in a line read, but not for multiple occurances in the same line.
You wanted that?
4.)
The identitation of your code seems wrong(at least of what you posted)
5.)
I dont understand your while loop ... seems not right, but I may be too tired to understand it.
Anyway, the way I would code it is (late at night that is):
CODE
my_file = ...
my_string = ...
infile = open(my_file,"r")
numlines = 0
found = 0
for line in infile:
numlines += 1
while 1:
str_found_at = line.find(my_string)
if str_found_at == -1:
#string not found in line ...
#go to next (ie break out of the while loop)
break
else:
#string found in line
found += 1
#more than once in this line?
#lets strip string and anything prior from line and
#then go through the testing loop again
line = line[str_found_at + len(string):]
infile.close()
print "%s was found %i times in %i lines", %string, %found, %numlines
edit:
even simpler:
CODE
my_file = ...
my_string = ...
infile = open(my_file,"r")
numlines = 0
found = 0
for line in infile:
numlines += 1
found += line.count(my_string)
infile.close()
print "%s was found %i times in %i lines", %string, %found, %numlines
This post has been edited by Nallo: 17 Sep, 2009 - 03:58 AM