在Python中执行多个字符串替换的最快实现 [英] Fastest implementation to do multiple string substitutions in Python
问题描述
除了对字符串执行replace
链接(即text.replace(a, b).replace(c, d).replace(e, f)...
)以外,是否有其他建议的方法来进行多个字符串替换?
例如,您将如何实现行为类似于Python中PHP htmlspecialchars
的快速功能?
Is there any recommended way to do multiple string substitutions other than doing replace
chaining on a string (i.e. text.replace(a, b).replace(c, d).replace(e, f)...
)?
How would you, for example, implement a fast function that behaves like PHP's htmlspecialchars
in Python?
我比较了(1)多个replace
方法,(2)正则表达式方法和(3)Matt Anderson方法.
I compared (1) multiple replace
method, (2) the regular expression method, and (3) Matt Anderson's method.
运行n = 10,结果如下:
With n=10 runs, the results came up as follows:
在100个字符上:
TIME: 0 ms [ replace_method(str) ]
TIME: 5 ms [ regular_expression_method(str, dict) ]
TIME: 1 ms [ matts_multi_replace_method(list, str) ]
在1000个字符上:
TIME: 0 ms [ replace_method(str) ]
TIME: 3 ms [ regular_expression_method(str, dict) ]
TIME: 2 ms [ matts_multi_replace_method(list, str) ]
在10000个字符上:
On 10000 characters:
TIME: 3 ms [ replace_method(str) ]
TIME: 7 ms [ regular_expression_method(str, dict) ]
TIME: 5 ms [ matts_multi_replace_method(list, str) ]
在100000个字符上:
On 100000 characters:
TIME: 36 ms [ replace_method(str) ]
TIME: 46 ms [ regular_expression_method(str, dict) ]
TIME: 39 ms [ matts_multi_replace_method(list, str) ]
在1000000个字符上:
On 1000000 characters:
TIME: 318 ms [ replace_method(str) ]
TIME: 360 ms [ regular_expression_method(str, dict) ]
TIME: 320 ms [ matts_multi_replace_method(list, str) ]
在3687809个字符上:
On 3687809 characters:
TIME: 1.277524 sec [ replace_method(str) ]
TIME: 1.290590 sec [ regular_expression_method(str, dict) ]
TIME: 1.116601 sec [ matts_multi_replace_method(list, str) ]
Matt对于在相当大的输入字符串上击败multi replace
方法表示敬意.
So kudos to Matt for beating the multi replace
method on a fairly large input string.
有人想过用较小的弦子敲打它吗?
Anyone got ideas for beating it on a smaller string?
推荐答案
通常,.replace
方法胜过所有其他方法. (请参阅上面的基准测试.)
Normally, .replace
method beats all other methods. (See my benchmarks above.)
这篇关于在Python中执行多个字符串替换的最快实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!