2016-03-01 62 views
0

我想检查a中的内容是否在内容b中。 对于每个项目,我想检查a中的内容是否位于b中(不管顺序如何)。搜索是否存在从一个文件到另一个文件的行

我可以做下面的事情,但它必须匹配甚至排序。如果a.txt中的项目存在于b.txt文件中,最好的方法是逐一打印出真实的文件?

f1 = open("a.txt").read().split("\n") 
f2 = open("b.txt").read().split("\n") 

for line in f1: 
    print f1 
for line in f2: 
    print f2 
print f1 == f2 

A.TXT

apple 
tomato 
green 
peach 
stack 
flow 
chance 

b.txt

stack 
peach 
blue 
green 
tomato 
wax 

结果

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

回答

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

尽管此代码可以回答这个问题,提供有关为什么和/或如何代码回答了这个问题提高了其长期价值的其他方面。 – Ajean

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 
+0

使用'set'将允许'如果line in bLines'操作更快 –

+0

好!添加了你的建议 –

+0

好吧,我提供了我自己的答案:) –

1

不管顺序?使用一套!

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