Searching for a list of strings in a file with Python

Dave Angel davea at davea.name
Mon Oct 14 09:06:31 EDT 2013


On 14/10/2013 01:34, Starriol wrote:

> Hi guys,
>
> I'm trying to search for several strings, which I have in a .txt file line by line, on another file.
> So the idea is, take input.txt and search for each line in that file in another file, let's call it rules.txt.
>
> So far, I've been able to do this, to search for individual strings:
>
> [code]import re
>
> shakes = open("output.csv", "r")
>
> for line in shakes:
>     if re.match("STRING", line):
>         print line,[/code]
>
> How can I change this to input the strings to be searched from another file?
>
> So far I haven't been able to.
>
> Thanks for the ideas.

Take your existing code, and make the bulk of it into a function
definition.  The function should take the 'string' as a parameter.

Once you've got that debugged, you can write code that reads your
pattern file, and for each line of it, calls the function you just
wrote.

You can certainly do it the way Peter describes, but if you learn to
factor each problem into separate functions (or classes, or generator,
or decorator, or ...) then your code will be easier to test, easier to
understand, and easier to reuse.


-- 
DaveA





More information about the Python-list mailing list