Grep in Python
Stefan Kirchberg
stefan.kirchberg at web.de
Thu Jun 20 12:29:21 EDT 2002
coolslife wrote:
>>>I saw that lots of people have implemented their own version of grep
>>>and most have called it "pygrep". (Am I right about that?). Since this
>>>is a resource consuming activity, does anyone have any idea what
>>>might be a optimum way to implement this?
>>See "NR-grep: A Fast and Flexible Pattern Matching Tool", by Gonzalo
>>Navarro, at http://www.dcc.uchile.cl/~gnavarro/ps/spe01.ps.gz for how
>>to search text fast.
>
> Thanx for your replies.
> are there any other resources I can look up?
Since grep uses Regular Expressions, you might want to have a look at
the standard module 're'. One could try something like the following
example. It's quite simple (because it's Python ;-)
>>>>>>>>>>>>>>>>snip
import re, sys
# your search expression here, maybe
pat = sys.argv[1]
# your input text filename, maybe
fname = sys.argv[2]
# now scan the textfile
for line in open("C:/temp/test.txt").readlines():
if re.search(pat, line):
print line,
# that's it.
<<<<<<<<<<<<<<<<snap
Hope this helps. Sure it's not perfect... ;-)
Stefan
More information about the Python-list
mailing list