python加速这个正则表达式子

Eul*_*lie 6 python regex

p = re.compile('>.*\n')
p.sub('', text)
Run Code Online (Sandbox Code Playgroud)

我想删除所有以'>'开头的行.我有一个非常大的文件(3GB),我处理大小为250MB的块,所以变量"text"是一个250MB的字符串.(我尝试了不同的大小,但整个文件的性能始终相同).

现在,我可以以某种方式加速这个正则表达式吗?我尝试了多行匹配,但速度慢了很多.还是有更好的方法?

(我已经尝试拆分字符串然后过滤掉这样的行,但它也慢了(我也试过一个lambda而不是def del_line :(可能不是工作代码,它只是来自内存):

def del_line(x): return x[0] != '>'

def func():
    ....
    text = file.readlines(chunksize)
    text = filter(del_line, text)
    ... 
Run Code Online (Sandbox Code Playgroud)

编辑:正如评论中所建议的那样,我也尝试逐行行走:

text = []
for line in file:
    if line[0] != '>':
        text.append(line)
text = ''.join(text)
Run Code Online (Sandbox Code Playgroud)

那也慢,需要~12秒.我的正则表达需要~7秒.(是的,这很快,但它也必须在较慢的机器上运行)

编辑:当然,我也试过str.startswith('>'),它更慢......

Joh*_*nal 0

这样不是更快吗?

def cleanup(chunk):
    return '\n'.join(st for st in chunk.split('\n') if not(st and st[0] == '>'))
Run Code Online (Sandbox Code Playgroud)

编辑:是的,那并不快。那慢了一倍。

也许可以考虑使用 subprocess 和 grep 之类的工具,正如 Ryan P 所建议的那样。您甚至可以利用多重处理。