【发布时间】:2013-09-12 23:08:58
【问题描述】:
我有许多文件,我想用另一个替换特定字符串的所有实例。
我目前有这个代码:
mappings = {'original-1': 'replace-1', 'original-2': 'replace-2'}
# Open file for substitution
replaceFile = open('file', 'r+')
# read in all the lines
lines = replaceFile.readlines()
# seek to the start of the file and truncate
# (this is cause i want to do an "inline" replace
replaceFile.seek(0)
replaceFile.truncate()
# Loop through each line from file
for line in lines:
# Loop through each Key in the mappings dict
for i in mappings.keys():
# if the key appears in the line
if i in line:
# do replacement
line = line.replace(i, mappings[i])
# Write the line to the file and move to next line
replaceFile.write(line)
这工作正常,但是对于映射的大小和我正在处理的文件的大小来说非常慢。
例如,在“映射”字典中有 60728 个键值对。 我需要处理多达 50 个文件,并将“key”的所有实例替换为相应的值,这 50 个文件中的每个文件大约有 250000 行。
还有多个实例需要在一行上替换多个键,因此我不能只找到第一个匹配项然后继续。
所以我的问题是:
有没有更快的方法来完成上述操作? 我曾考虑过使用正则表达式,但我不确定如何制作一个使用字典中的键/值对进行多次内联替换的方法。
如果您需要更多信息,请告诉我。
【问题讨论】:
-
链接的重复问题有无法置顶的答案。
-
链接的问题有一个 更小的替换字典。鉴于问题是关于性能的,我对这种差异无法区分问题的想法感到困惑。
-
如果你不一次做一行,它会快很多。由于您可以将整个文件读入内存,因此只需执行此操作并为每个术语进行一次替换。
-
@SteveJessop:我认为在那里添加另一个答案会更有用,它用更大的字典重复 Tor Valamo 的测试,而不是并行有一个完全独立的问题和答案......
-
另外,我敢打赌优化
if i in line: line = line.replace(i, mappings[i])实际上会让你慢很多。想一想:当没有找到时,你正在做一个完整的搜索,所以你可以跳过一个完整的搜索,没有任何好处;找到后,您将搜索两次而不是一次。
标签: python regex dictionary replace