searching for the number of occurences of a string
jstroud at ucla.edu
Mon Mar 6 02:37:45 CET 2006
> say i have a text file with a string ( say '(XYZ)') and I want to find
> the number of line where this string has occured. What is the best way
> to do that?
> what about if that string was say a 0 with leading and trailing white
> spaces, would that be any different?
> moe smadi
To read every line in a file:
afile = open(filename)
for aline in afile:
To see if a string contains another string, try
if another_string() in astring:
If you need regular expressions, see the re module.
regex = re.compile(r'(?:\s+0\s+)|\(XYZ\)')
print regex.search(' 0 ').group()
print regex.search(' (XYZ) abc').group()
That should be everything you could possibly need. Its up to you to put
it all together.
UCLA-DOE Institute for Genomics and Proteomics
Los Angeles, CA 90095
More information about the Python-list