批量字符串`replace`?

时间:2013-06-28 07:53:29

标签: python replace str-replace batch-processing batch-rename

使用系统库,效率非常低:

foo = "foo bar car haz can bar foo"
repl = {('foo', 'bar'), ('car', 'bar'), ('foo', 'haz')}

for rep in repl:
    foo = foo.replace(rep)

替换批次replace应该在O(| foo | + | repl |)而不是O(| foo |×| repl |)中解决此问题,如上述方法。

您能想到实现这种更有效解决方案的简洁方法吗?

1 个答案:

答案 0 :(得分:1)

使用正则表达式

import re

foo = "foo bar car haz can bar foo"

re.sub(r"(foo|car)", "bar", foo)

> 'bar bar bar haz can bar bar'

实际上在这种情况下速度较慢:

import timeit

timeit.timeit('re.sub(r"(foo|car)", "bar", "foo bar car haz can bar foo")', 'import re', number=10000)

> 0.051492929458618164

def test():
    foo = "foo bar car haz can bar foo"
    repl = [('foo', 'bar'), ('car', 'bar'), ('foo', 'haz')]
    for rep in repl:
        foo = foo.replace(*rep)

timeit.timeit("test()", setup="from __main__ import test", number=10000)

> 0.026629924774169922