2016-03-01 57 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 
相關問題