所以我有一个大的文本文件,大约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)
您不应该在每一行打开和关闭输出文件。更重要的是,您可以存储每个
concept_phrase
的替换,并避免对concept_phrases
的翻译版本进行替换(k是概念短语的数量,n是行的数量):str.replace
通常速度很快,我怀疑用re.sub
一次替换就能打败它,即使重复调用str.replace
。你知道吗我建议使用
cython
模块编译文件并尝试运行它。它会加速你的代码。你知道吗相关问题 更多 >
编程相关推荐