searching for the number of occurences of a string
James Stroud
jstroud at ucla.edu
Sun Mar 5 20:37:45 EST 2006
M.N.A.Smadi wrote:
> hi;
> 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?
>
> thanks
> moe smadi
Some pieces:
To read every line in a file:
afile = open(filename)
for aline in afile:
do_something_here()
To see if a string contains another string, try
if another_string() in astring:
do_something_else_here()
If you need regular expressions, see the re module.
For instance:
import re
regex = re.compile(r'(?:\s+0\s+)|\(XYZ\)')
print regex.search(' 0 ').group()
print regex.search(' (XYZ) abc').group()
if regex.search('abcdefg'):
print 'yep'
else:
print 'nope'
That should be everything you could possibly need. Its up to you to put
it all together.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com/
More information about the Python-list
mailing list