如何在另一个文件中搜索一个文件中的字符串

我需要在 python 中扫描 2 个文件,并说出 file1 中的哪些单词也在 file2 中。我制作了一个包含 file2 中所有单词的列表,然后扫描 file1 中的行是否在列表中。


所以这工作得很好,但是大文件(比如 500k)可能需要 1 小时以上,我想知道是否有更快的方法


提前致谢


(defined var etc and files)

a = []

for line in var:

    a += [line]

teller = 0


for line1 in new_file:

    if line1 not in a:

        print(line1, file=filter, end='')

    else:

        teller += 1

        print(line1, file=bad, end='' )


print('There were', teller, 'lines that were in the old file.')


慕运维8079593
浏览 93回答 3
3回答

aluckdog

更快的替代方法是使用集合(只要您可以将两个文件的内容保留在内存中):with open('a.txt', 'r') as a, open('b.txt', 'r') as b:    a_content = set(a)    b_content = set(b)result = a_content.intersection(b_content)

森林海

如果您担心速度,那么您应该使用操作系统设施,而不是 Python 循环。通常,查找单独行的最快方法是对两个文件进行排序,然后进行简单的文件比较。如果你坚持使用Python,那也是一种更快的方法。

慕勒3428872

您的方法可以工作,但效率非常低,因为您正在遍历 file2 以查找 file1 中的每个单词/行。尝试将 file1 和 file2 都转为集合,然后比较集合;我很确定 Python 有类似 .intersect 或 .intersection 的东西来比较两个集合、列表、数组或其他数据结构。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python