Searching for a list of strings in a file with Python

This is the place for queries that don't fit in any of the other categories.

Searching for a list of strings in a file with Python

Postby starriol » Mon Oct 14, 2013 5:34 am

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: Select all
import re

shakes = open("output.csv", "r")

for line in shakes:
    if re.match("STRING", line):
        print line,


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.
starriol
 
Posts: 4
Joined: Fri Oct 11, 2013 3:24 pm

Re: Searching for a list of strings in a file with Python

Postby casevh » Mon Oct 14, 2013 6:07 am

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: Select all
import re

shakes = open("output.csv", "r")

for line in shakes:
    if re.match("STRING", line):
        print line,


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.


Just open the "rules.txt" file and read all the lines into a list. Then check each entry in that list with each line of your input file.

Untested....

Code: Select all
import re

# Read the matching test from rules.txt. Remove any
# white space (space, tab, end-of-line) from the strings to match.

matches = []
for line in open("rules.txt", "r"):
    matches.append(line.strip())

shakes = open("output.csv", "r")

for line in shakes:
    for match in matches:
        if re.match(match, line):
            print line,


casevh
casevh
 
Posts: 70
Joined: Sat Feb 09, 2013 7:35 am


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 5 guests

cron