在一个大的文本文件中基于一个大的短语列表替换短语的一种省时的方法

2024-10-03 02:45:38 发布

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

所以我有一个大的文本文件,大约900MB,我想逐行读取文件,对于每一行,根据短语列表中的项目,查找并替换,让我们假设一种情况

假设我有一个.txt文件,其中包含所有的wikipedia明文。你知道吗

我有一个python短语列表,称为p,p=['hello world','twently three','any bigram','any trigram'],p中的所有项目都是短语(不存在单个单词)

给定这个列表p,我试图逐行扫描.txt文件,并使用p检查当前行中是否存在任何p项,如果存在,请将单词之间的空格替换为“,”,例如,如果当前行显示:“hello world twently three any text goes here”,它应该替换为:“hello\u world twently\u three any text go here” P的长度是14000

我已经用python实现了这个,而且速度非常慢,它平均只能执行5000行/分钟的速度,这个.txt文件有数百万行,有没有什么有效的方法? 谢谢

更新:

with open("/media/saurabh/New Volume/wikiextractor/output/Final_Txt/single_cs.txt") as infile:
    for index,line in enumerate(infile):
        for concept_phrase in concepts:
            line = line.replace(concept_phrase, concept_phrase.replace(' ', '_'))
        with open('/media/saurabh/New Volume/wikiextractor/output/Final_Txt/single_cs_final.txt', 'a') as file:
            file.write(line +  '\n' )  
        print (index)

Tags: 文件项目texttxthello列表worldhere
2条回答

您不应该在每一行打开和关闭输出文件。更重要的是,您可以存储每个concept_phrase的替换,并避免对concept_phrases的翻译版本进行替换(k是概念短语的数量,n是行的数量):

in_file = "/media/saurabh/New Volume/wikiextractor/output/Final_Txt/single_cs.txt"
out_file = "/media/saurabh/New Volume/wikiextractor/output/Final_Txt/single_cs_final.txt"
replacement = dict([(cp, cp.replace(' ', '_')) for cp in concepts])

with open(in_file) as infile, open(out_file, 'a') as file:
    for line in infile:
        for concept_phrase in concepts:
            line = line.replace(concept_phrase, replacement[concept_phrase])
        file.write(line) 

str.replace通常速度很快,我怀疑用re.sub一次替换就能打败它,即使重复调用str.replace。你知道吗

我建议使用cython模块编译文件并尝试运行它。它会加速你的代码。你知道吗

相关问题 更多 >