2011-02-13 62 views
2

我使用python 2.6在Linux上。在一個文件中使用文本搜索賽在第二個文件

我有兩個文本文件 first.txt對每行文本的一個字符串。所以它看起來像

LOREM
議會聯盟
ASFD

第二個文件不相當有相同的格式。 它看起來更像是這個

1231 LOREM
1311 assss 311

我想借此從first.txt文本的每一行,並確定是否有在第二個文本匹配。如果沒有匹配,我想將缺失的文本保存到第三個文件。我想忽略情況,但並非完全必要。這就是爲什麼我在看正則表達式,但沒有多少運氣。

所以我打開文件,使用readlines方法()來創建一個列表。
遍歷列表並打印出匹配項。

這裏是我的代碼

first_file=open('first.txt', "r") 
first=first_file.readlines() 
first_file.close() 

second_file=open('second.txt',"r") 
second=second_file.readlines() 
second_file.close() 

while i < len(first): 
    j=search[i] 
    while k < len(second): 
    m=compare[k] 
    if not j.find(m): 
    print m 
    i=i+1 
    k=k+1 
exit() 

這絕對不是優雅。任何人都有建議如何解決這個問題或更好的解決方案?

+1

lorem`是否也匹配`somelorem`?整條線是否應該完全相同?應該只有單詞是相同的? – Wolph 2011-02-13 06:05:29

回答

3

我的做法是這樣的:閱讀的第二個文件,將其轉換成小寫,然後創建它包含的單詞列表。然後將此列表轉換爲set,以獲得更好的大文件性能。

然後通過在第一文件中的每一行,如果它(也被轉換爲小寫,並去除多餘的空格)是不是在我們創建的集,其寫入第三個文件。

with open("second.txt") as second_file: 
    second_values = set(second_file.read().lower().split()) 

with open("first.txt") as first_file: 
    with open("third.txt", "wt") as third_file: 
     for line in first_file: 
      if line.lower().strip() not in second_values: 
       third_file.write(line + "\n") 

設置對象是一個簡單的容器類型,它是無序的,不能包含重複的值。它旨在讓您快速添加或移除項目,或者確定項目是否已經在設置中。

with聲明以確保文件被關閉,即使發生異常的便捷方式。它們在Python 2.6以上版本中默認啓用,在Python 2.5中,它們要求您將行from __future__ import with_statements置於文件的頂部。

in運營商做什麼,它聽起來就像:告訴你,如果一個值可以在集合中找到。與列表一起使用時,它只是迭代遍歷,就像你的代碼一樣,但是當與一個set對象一起使用時,它使用散列執行得更快。 not in則相反。 (可能的困惑點:in也用於定義for循環(for x in [1, 2, 3]),但這是無關的。)

+0

我很感謝幫助! – RSolis 2011-02-13 06:45:59

1

假設你正在尋找第二個文件中的整條生產線:

second_file=open('second.txt',"r") 
second=second_file.readlines() 
second_file.close() 


first_file=open('first.txt', "r") 
for line in first_file: 
    if line not in second: 
     print line 

first_file.close() 
相關問題