问题描述:

My question is similar to this one, except that I want to search for the occurrence of multiple chars, for example g, d and e, and then print the line in which ALL the specified characters exist.

I have tried the following but it didn't work:

searchfile = open("myFile.txt", "r")

for line in searchfile:

if ('g' and 'd') in line: print line,

searchfile.close()

I was getting lines which had EITHER 'g' or 'd' or both in them, all I want is just both occurences, not at least one of them, as is the result of running the above code.

网友答案:

This line:

if ('g' and 'd') in line: 

is the same as

if 'd' in line:

because

>>> 'g' and 'd'
'd'

You want

if 'g' in line and 'd' in line:

or, better:

if all(char in line for char in 'gde'):

(You could use set intersection too, but that's less generalizable.)

网友答案:
if set('gd').issubset(line)

This has the advantage of not going through twice as each check of c in line iterates through the entire line

网友答案:

regular expressions will certainly help you when it comes to pattern matching, but it seem s that your search is easier than this. Try the following:

# in_data, an array of all lines to be queried (i.e. reading a file)
in_data = [line1, line2, line3, line4]

# search each line, and return the lines which contain all your search terms
for line in in_data:
    if ('g' in line) and ('d' in line) and ('e' in line):
        print(line)

Something this simple should work. I am making a few assumptions here: 1. the order of the search terms does not matter 2. upper / lower case is not dealt with 3. the frequency of the search terms is not considered.

Hope it helps.

相关阅读:
Top