簡體   English   中英

如何使用Python比較兩個文件並提取一些數據

[英]How to compare two files and extract some data with Python

我有2個文件:file1,file2。 file2包含所有file1以及更多文件。 例:

file1:
data1/111 
data2/222 
data3/333 

file2:
data1/111 \ewr\xcgf\wer 54645623456.xml
data23/42234 \asdqw\aqerf 23525.xml
data2/222 \asd\qwe 234234.xml
data66/2331 \a53\fdf355 12312333311.xml
data3/333 \from\where 123123.xml
data4/444 \xcv\sdf\ghf 98546.xml 
and MANY more...

因此,我正在嘗試打印出file2中兩個文件中都存在的行。 這意味着打印出來的每一行都必須有多余的數據。 像路徑和XML文件名。

我試過了;

lines1 = open(path1).readlines()
lines2 = open(path2).readlines()

for i in lines1:
    for j in lines2:
        if i in j:
            print(j.rstrip())

這將打印第lines2所有行,但是我想找出的是; 搜索從第一行lines1lines2 ,如果在任何地方發現它lines2 ,打印從該行lines2 ,所以等等。 所以在那之后,它應該對lines1的第二行執行相同的lines1

有人可以幫忙嗎?

感謝您的時間。

lines1 = open(path1).readlines()
lines2 = open(path2).readlines()

for l1 in lines1:
    if l1 in lines2:
        print(l1)

或使用列表理解:

lines1 = open(path1).readlines()
lines2 = open(path2).readlines()
print([line for line in lines1 if line in lines2])

這個問題還不是很清楚,但是如果您知道行數相同但在某些情況下有更多的數據用於file2,則可以對O(n)解決方案執行以下操作:

lines1 = open(path1).readlines()
lines2 = open(path2).readlines()

for line1, line2 in zip(lines1, lines2):
    if line1 != line2:
        print line2.rstrip()

我有一個交叉檢查的解決方案;

lines1 = open(path1).readlines()
lines2 = open(path2).readlines()

for i in lines1:
    for j in lines2:
        if j.startswith(i.rstrip()):
            print(j.rstrip())
            break

它的作用是:從lines1 1行中搜索lines1所有lines2 break防止重復

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM