【问题标题】:How to search a string in a file in another file如何在另一个文件中的文件中搜索字符串
【发布时间】:2021-01-21 15:00:58
【问题描述】:

我需要在 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.')

【问题讨论】:

    标签: python file for-loop search


    【解决方案1】:

    一种更快的替代方法是使用集合(只要您可以将两个文件的内容都保存在内存中):

    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)
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您的方法可以工作,但效率极低,因为您要遍历 file2 中的每个单词/行。尝试将 file1 和 file2 都转换为集合,然后比较集合;我很确定 Python 有类似 .intersect 或 .intersection 的东西来比较两个集合、列表、数组或其他数据结构。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-21
          • 2011-02-04
          • 2023-03-17
          • 1970-01-01
          • 2014-02-13
          相关资源
          最近更新 更多