我有两个文件,其中有很多列和关于一堆对象的不同信息,它们带有对象 ID。我需要找到两个文件之间的匹配项,但对象 ID 有两种不同的格式:
一个文件中的 12-12-1 在另一个文件中将写为 0012 00012 1。例如,在一个文件中我有:
0001 01531 1
0001 01535 1
0001 01538 1
对应的是另一个:
1-1531-1
1-1535-1
1-1538-1
像
这样简单的东西matches = open('matches.dat','w')
for j in range(len(file1)):
for i in range(len(file2)):
if file1[j] == file2[i]:
matches.write('{}/n'.format(file1[j]))
似乎并没有成功。
这里的 file1 和 file2 是包含来自不同文件的所有对象 ID 的列表。
我应该在我的代码中添加什么来找到匹配项?
请您参考如下方法:
将第一种格式转换为第二种格式:
import re
def convert(word):
word = word.strip().replace(' ', '-')
return re.sub('\\b0+', '', word) # strip all 0s after a word boundary (space or beginning of line)
算法改进
您可以通过将两者转换为列表并计算交集来在 O(n+m) 时间内计算交集
file1_ids = {convert(line) for line in file1}
file2_ids = {line for line in file2}
matches = file1_ids.intersection(file2_ids)
