搜索是否存在从一个文件到另一个文件的行

时间:2016-03-01 23:54:59

标签: python

我想检查a中的内容是否在内容b中。 对于每个项目,我想检查a中的内容是否位于b(无论顺序如何)。

我可以做类似下面的事情,但它必须与订购相匹配。如果a.txt中的项目存在于b.txt中,那么一个接一个地打印出来的最佳方法是什么?

stack
peach
blue
green
tomato
wax

A.TXT

apple -> false
tomato -> true
green -> true
peach -> true
stack -> true
flow -> false
chance -> false

b.txt

{{1}}

结果

{{1}}

3 个答案:

答案 0 :(得分:2)

无论订单如何?使用一套!

with open('a.txt') as f_a, open('b.txt') as f_b:
    a_lines = set(f_a.read().splitlines())
    b_lines = set(f_b.read().splitlines())
for line in a_lines:
    print(line, '->', line in b_lines)

输出

tomato -> True
peach -> True
chance -> False
green -> True
apple -> False
stack -> False
flow -> False

答案 1 :(得分:0)

这对你有用。

with open('a.txt') as f, open('b.txt') as g:
        bLines = set([thing.strip() for thing in g.readlines()])
        for line in f:
            line = line.strip()
            if line in bLines:
                print line, "->", "True"
            else:
                print line, "->", "False"

输出

apple -> False
tomato -> True
green -> True
peach -> True
stack -> True
flow -> False
chance -> False

答案 2 :(得分:-1)

for line in f1:
    if line in f2:
        print("true")