比较两个文本文件并导出匹配的Python

2024-09-29 23:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有1个文本文件(tab del),有15000条记录。 我有另一个文本文件(tab del),有5000条记录。在

在包含5000条记录的文件中,有一些行与包含15000条记录的文件相匹配。这些可以通过名为URN(唯一记录号)的列标题进行标识。例如,我可能需要从主文件中取出urn62294,但是我不知道我必须取出这个文件,直到我比较了两个文件并看到它都在两个文件中。在

在python中实现这一点有多困难?在


Tags: 文件标题记录tab标识文本文件delurn
3条回答

难吗?不,你可以很容易地

file1 = open("file1.txt","r")
results = []

for line in file1:
    file2 = open("file2.txt","r")
    for l in file2:
        if (l.split("\t")[0] == line.split("\t")[0]):
            results.append(l.split("\t")[0])
            break
    file2.close()
file1.close()

for i in results:
    print(i)

现在,这是最好的方法吗?可能不适合大文件。 (我花了74秒处理你的文件)。在

您可以查看Pandas库。它允许您将两个表作为数据帧加载,并以类似sql的方式将它们连接到所需的列上。文档应该很容易。在

尝试使用pip install pandas安装pandas

然后运行这个:

import pandas as pd

filename1 = #main file
filename2 = #the other file
main = pd.read_csv(filename1,sep='\t') # sep='\t' is for tab delimited file
side = pd.read_csv(filename2,sep='\t')
main['URN'] = main['URN'].astype(int)
side['URN'] = side['URN'].astype(int)
merge = pd.merge(main,side,on='URN',how='inner') #how=inner means the URN value is in both 2 files
#merge = merge[merge['URN'] != 62294]
print (merge)
merge.to_excel('Output.xlsx,index=False)

相关问题 更多 >

    热门问题