在listfile Python中搜索多个关键字的文件

时间:2018-02-06 09:17:01

标签: python windows python-2.7 list search

我有一个脚本在文件(X)中搜索关键字但是,我想用文件(y)搜索包含多个关键字的文件(X)。

来源:

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

输出:

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 . . .

我想要的是什么:

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 . . .

我希望ColorSelect = 'Brown'类似ColorSelect = file_containing_words_to_search_for.txt又名[file(Y)]

1 个答案:

答案 0 :(得分:1)

来自fileX的lines1和来自fileY的linesy

common = set(lines1) & set(linesy)

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

例如

如下所示...

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!'

但如果你想找到不存在的颜色,那么:

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' 
相关问题