MALKAVIAN
MALKAVIAN

Reputation: 131

Search file for multiple keywords in listfile Python

I have a script which searches file(X) for a keyword however, I want to search file(X) with file(y) which contains multiple keywords.

Source:

lines1 = [line1.rstrip('\n') for line1 in open('file(X)')]
print'------'
print lines1
print'------'
Colors = lines1
ColorSelect = 'Brown'
while str.upper(ColorSelect) != "QUIT":
    if (Colors.count(ColorSelect) >= 1):
        print'The color ' + ColorSelect + ' exists in the list!' 
        break
    elif (str.upper(ColorSelect) != "QUIT"):
        print'The list does not contain the color ' + ColorSelect
        break

Output:

C:\Users\Foo\Bar\Python\Test\>C:\python27\python Test.py
------
['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Brown']
------
The color Brown exists in the list!


Press any key to continue . . .

What I want:

C:\Users\Foo\Bar\Python\Test\>C:\python27\python Test.py
------
['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Brown']
------
The color Brown exists in the list!
The color Yellow exists in the list!
The color Red exists in the list!


Press any key to continue . . .

I would like ColorSelect = 'Brown' to be something like ColorSelect = file_containing_words_to_search_for.txt aka[file(Y)]

Upvotes: 1

Views: 77

Answers (1)

quamrana
quamrana

Reputation: 39354

Given lines1 from fileX and linesy from fileY:

common = set(lines1) & set(linesy)

for color in common:
   print 'The color ' + color + ' exists in the list!' 

e.g

something like below...

lines1 = [line1.rstrip('\n') for line1 in open('fileX.txt')]

lines2 = [line2.rstrip('\n') for line2 in open('fileY.txt')]

common = set(lines1) & set(lines2)

for color in common:
   print 'The color ' + color + ' exists in the list!'

But if you want to find colours not present then:

set_of_lines1 = set(lines1)
set_of_lines2 = set(lines2)
common = set_of_lines1 & set_of_lines2
difference = set_of_lines2 - set_of_lines1

for color in difference:
   print 'The color' + color + 'does not exist in the list' 

Upvotes: 1

Related Questions