我有 2 个文件,我想从 file2(fsearch) 中获取包含 file1(forig) 中任何给定行的所有行
我写了一个简单的 python 脚本,看起来像这样:
def search_string(w, file):
global matches
reg = re.compile((r'(^|^.*\|)' + w.strip("\r\n") + r'(\t|\|).*$'), re.M)
match = reg.findall(file)
matches.extend(match)
fsearch_text = fsearch.read()
for fword in forig:
search_string(fword, fsearch_text)
file1 大约有 100,000 行,file2 大约有 200,000 行,所以我的脚本大约需要 6 个小时才能完成。
是否有更好的算法可以在更短的时间内实现相同的目标?
编辑:
我应该提供示例来说明为什么我需要正则表达式:
我正在搜索 file1 中的单词列表,并尝试将它们与 file2 中的翻译相匹配。如果我不使用正则表达式来限制可能的匹配,我还会匹配仅包含我搜索的单词本身的单词的翻译,例如:
我搜的词:浸し
对应词:お浸し|御浸し|御したし &n bobito-flavored soy sauce (蔬菜小菜)
所以我必须用 ^ 或 | 来限制匹配的开始,用\t 或 | 来限制匹配的结束,但是捕获整行
最佳答案
假设您可以在内存中同时拥有这两个文件。您可以阅读它们并对其进行排序。
之后,您可以对线进行线性比较。
f1 = open('e:\\temp\\file1.txt')
lines1 = sorted([line for line in f1])
f2 = open('e:\\temp\\file2.txt')
lines2 = sorted([line for line in f2])
i1 = 0
i2 = 0
matchCount = 0
while (i1 < len(lines1) and i2 < len(lines2)):
line1 = lines1[i1]
line2 = lines2[i2]
if line1 < line2:
i1 += 1
elif line1 > line2:
i2 += 1
else:
matchCount += 1
i2 += 1
print('matchCount')
print(matchCount)
关于使用正则表达式的 Python 跨文件搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888925/