regex - Matching lines with an AND operator in Python -



regex - Matching lines with an AND operator in Python -

i have written code below finding lines in infile matches of keywords in keyword file. problem is, want lines of infile contain of keywords. seems harder thought, beginner guess missing obvious. regex doesn't seem have straightforward 'and' operator however.

import re infile = open('path/#input.txt', 'r') outfile = open('path/#output.txt', 'w') # read textfile containing keywords find # (and strip newline character '\n') keywords = [line.strip() line in open('path/#keywords.txt')] # compile keywords regex pattern pattern = re.compile('|'.join(keywords)) # see lines in infile match of keywords # , write lines outfile line in infile: if pattern.search(line): outfile.write(line)

regular expressions not swiss regular army knife capable of solving every problem. aren't solution problem:

there no way utilize one regexp operation kind of conjuction operation looking for. regexp shouldn't used plain-text searches, since "plain-text" keywords can contain characters trigger different behavior in regexps (such . or $)

try this, using 1 for loop within other iterate through keywords each line:

keywords = ... line in infile: # iterate through keywords found_all = true kw in keywords: # if keyword not found, found_all = false if kw not in line: found_all = false if found_all: outfile.write(line)

update: @stefano sanfilippo's solution more concise version of same thing. :)

python regex

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -