简化用于txt搜索的python代码

2024-10-04 09:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,我需要检查一个巨大的txt文件中是否存在给定的字符串集。到目前为止,我已经编写了这段代码,它在我的数据库的一个子样本上运行没有问题。问题是,在搜索整个数据库时需要10多个小时,我正在寻找一种方法来加快这个过程。你知道吗

到目前为止,代码从我拼凑的txt文件中读取字符串列表(列表.txt)搜索数据库中每一行的每一项(hugedataset.txt文件). 我的最终输出应该是数据库中存在的项的列表(或者,不存在的项的列表)。我打赌有一个更有效的方法来做事情,虽然。。。你知道吗

谢谢你的支持!你知道吗

import re
fobj_in = open('hugedataset.txt')
present=[]

with open('list.txt', 'r') as f:
    list1 = [line.strip() for line in f]

print list1  

for l in fobj_in:
    for title in list1:
       if title in l:
          print title
          present.append(title)

set=set(presenti)   
print set

Tags: 文件方法字符串代码intxt数据库列表
2条回答

因为您不需要任何每行信息,所以可以一次搜索整个字符串:

data = open('hugedataset.txt').read()  # Assuming it fits in memory
present=[]  # As @svk points out, you could make this a set

with open('list.txt', 'r') as f:
    list1 = [line.strip() for line in f]

print list1  

for title in list1:
   if title in data:
      print title
      present.append(title)

set=set(present)   
print set

您可以使用regexp通过一次传递检查所有子字符串。例如,看下面的答案:Check to ensure a string does not contain multiple values

相关问题 更多 >