python正则表达式关于芬德尔执行时间太长

2024-04-25 23:57:12 发布

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

我要删除文件中以点“.”结尾的所有单词。我的文件大约是15MB,会有超过400000字。我用re.findall来找到这样的词并替换它们。你知道吗

for w in re.findall(r'([a-zA-Z0-9]+\.)', test_dict):
    test_dict = test_dict.replace(w, ' ')

这需要很长时间来执行。有没有提高性能的方法或其他替代方法来查找和替换这些词?你知道吗


Tags: 文件方法intestrefor结尾性能
2条回答

在Python中,可以一行一行地循环一个文件,一行一个字地循环一个文件。你知道吗

所以你可以考虑:

with open(your_file) as f_in, open(new_file, 'w') as f_out:
    for line in f_in:
         f_out.write(' '.join(w for w in line.split() if not w.endswith('.')+'\n')
# then decide if you want to overwrite your_file with new_file

您可以尝试使用re.sub,而不是循环使用re.findall的结果。你知道吗

# Example text:
text = 'this is. a text with periods.'

re.sub(r'([a-zA-Z0-9]+\.)', ' ', text)

这将返回与循环相同的结果:

'this   a text with  '

在一个相对较小的文档(179KB,Romeo and Juliet)上,re.findall循环大约需要0.369秒,re.sub大约需要0.0091秒。你知道吗

相关问题 更多 >