2017-03-01 114 views
0

目前卡住了一個小任務,我有兩個.txt文件,我想找到任何匹配的單詞出現在兩個並輸出結果到一個新的文件,但下面的代碼只顯示空白文件,任何想法我需要改變或看看。Python文件匹配

file1 example file2 example 
12345 565  543252 
54321 ff df  12345 
0000 ff f0  11111 

理想爲12345在這兩個文件匹配,應該打印線從文件1 12345 565到輸出文件。

with open('Results.txt', 'r') as file1: 
    with open('test.txt', 'r') as file2: 
     same = set(file1).intersection(file2) 

same.discard('\n') 

with open('matches.txt', 'w') as file_out: 
    for line in same: 
     file_out.write(line) 

任何幫助將感激地收到。

回答

0

與您的代碼的問題是,file1第一行居然是:

12345 565 

線和第二線從file2只有:

12345 

您的代碼將無法工作,因爲intersect會試圖匹配這個不同的線路。

你可以做的是:

with open('Results.txt', 'r') as file1: 
    with open('test.txt', 'r') as file2: 
     a = set(x.split()[0] for x in file1) 
     b = [x.rstrip() for x in file2] 
     same = a.intersection(b) 

same.discard('\n') 

print same 

輸出:set(['12345'])

注意此方法從file1只使用了第一列,因此任何其他比賽與其他列將無法正常工作。希望這可以幫助

+0

非常感謝,完美的作品!出於興趣,可以從file1打印完整行?即12345 565? – here2learn