Searching a file for multiple strings (PS)
Tim Chase
python.list at tim.thechases.com
Sat Jan 31 15:00:27 EST 2009
>> I'm fairly new with python and am trying to build a fairly simple
>> search script. Ultimately, I'm wanting to search a directory of files
>> for multiple user inputted keywords. I've already written a script
>> that can search for a single string through multiple files, now I just
>> need to adapt it to multiple strings.
One more item: if your files are large, it may be more efficient
to scan through them incrementally rather than reading the whole
file into memory, assuming your patterns aren't multi-line (and
by your escaping example, I suspect they're just single-words):
items = set(['a', 'b', 'c'])
for fname in ['file1.txt', 'file2.txt']:
still_to_find = items.copy()
for line in file(fname):
found = set()
for item in still_to_find:
if item in line:
found.add(item)
still_to_find.difference_update(found)
if not still_to_find: break
if still_to_find:
print "%s: Nope" % fname
else:
print "%s: Yep" % fname
just one more way to do it :)
-tkc
More information about the Python-list
mailing list