Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Searching for a list of strings in a file with Python

1,230 views
Skip to first unread message

Starriol

unread,
Oct 14, 2013, 1:34:43 AM10/14/13
to
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.

Peter Otten

unread,
Oct 14, 2013, 2:33:41 AM10/14/13
to pytho...@python.org
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?

Assuming every line in input.txt contains a regular expression and you don't
care which one matches:

shakes = open("output.csv")

# you will iterate over the regex multiple times,
# so put them in a list
rattles = [line.strip() for line in open("input.txt")]

for line in shakes:
for expr in rattles:
if re.match(expr, line):
print line,
break # out of the for-rattles loop
# at the first matching regex

Dave Angel

unread,
Oct 14, 2013, 9:06:31 AM10/14/13
to pytho...@python.org
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


Denis McMahon

unread,
Oct 14, 2013, 4:38:56 PM10/14/13
to
read all the search strings into a list

while there's data in shakes
read a line from shakes
for each string in search string list
search the line from shakes for the search string

--
Denis McMahon, denismf...@gmail.com
0 new messages