My question is similar to this one, except that I want to search for the occurrence of multiple
chars, for example
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,
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.
if ('g' and 'd') in line:
is the same as
if 'd' in line:
>>> 'g' and 'd' 'd'
if 'g' in line and 'd' in line:
if all(char in line for char in 'gde'):
(You could use set intersection too, but that's less generalizable.)
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.