使用正则表达式的 Python 跨文件搜索

标签 python regex algorithm

我有 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/

相关文章:

仅包含字母数字字符和下划线的正则表达式,以字母字符开头

c++ - 使用尾递归查找数组的最小元素

c - 如何从 C 文件中读取最后 n 行

python - 如何改 rebase 类

php - 我们如何在 php 中突出显示完整单词和部分单词?

python - Python 中的 SGML 解析器

php - 正则表达式捕获 : repeating two letters

c++ - 从所有组合的假设列表中获取索引排列的算法?

python - uWSGI [+ nginx] 文件描述符错误(没有这样的文件或目录)

Python 求质因数