python replace替换多个字符_使用Python替换多个字符

替换两个字符

我计算了当前答案中的所有方法以及一个额外的方法。

使用输入字符串abc&def#ghi并替换& - > \&和# - >#,最快的方法是将替换组合在一起,如:text.replace('&', '\&').replace('#', '\#')。

每项功能的时间:

a)1000000个循环,最佳3:每循环1.47μs

b)1000000个循环,最佳3:每循环1.51μs

c)100000个循环,最佳3:每循环12.3μs

d)100000个循环,最佳3:12μs/循环

e)100000个循环,最佳3:每循环3.27μs

f)1000000个循环,最佳3:每循环0.817μs

g)100000个循环,最佳为每循环3:3.64μs

h)1000000个循环,最佳3:每循环0.927μs

i)1000000个循环,最佳3:每循环0.814μs

以下是功能:

def a(text):

chars = ""

for c in chars:

text = text.replace(c, "\\" + c)

def b(text):

for ch in ['&','#']:

if ch in text:

text = text.replace(ch,"\\"+ch)

import re

def c(text):

rx = re.compile('([])')

text = rx.sub(r'\\\1', text)

RX = re.compile('([])')

def d(text):

text = RX.sub(r'\\\1', text)

def mk_esc(esc_chars):

return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])

esc = mk_esc('')

def e(text):

esc(text)

def f(text):

text = text.replace('&', '\&').replace('#', '\#')

def g(text):

replacements = {"&": "\&", "#": "\#"}

text = "".join([replacements.get(c, c) for c in text])

def h(text):

text = text.replace('&', r'\&')

text = text.replace('#', r'\#')

def i(text):

text = text.replace('&', r'\&').replace('#', r'\#')

时间如下:

python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"

python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"

替换17个字符

这里有类似的代码来做同样的事情,但有更多的字符要逃避(\`* _ {}>#+ - 。!$):

def a(text):

chars = "\\`*_{}[]()>#+-.!$"

for c in chars:

text = text.replace(c, "\\" + c)

def b(text):

for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:

if ch in text:

text = text.replace(ch,"\\"+ch)

import re

def c(text):

rx = re.compile('([])')

text = rx.sub(r'\\\1', text)

RX = re.compile('([\\`*_{}[]()>#+-.!$])')

def d(text):

text = RX.sub(r'\\\1', text)

def mk_esc(esc_chars):

return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])

esc = mk_esc('\\`*_{}[]()>#+-.!$')

def e(text):

esc(text)

def f(text):

text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')

def g(text):

replacements = {

"\\": "\\\\",

"`": "\`",

"*": "\*",

"_": "\_",

"{": "\{",

"}": "\}",

"[": "\[",

"]": "\]",

"(": "\(",

")": "\)",

">": "\>",

"#": "\#",

"+": "\+",

"-": "\-",

".": "\.",

"!": "\!",

"$": "\$",

}

text = "".join([replacements.get(c, c) for c in text])

def h(text):

text = text.replace('\\', r'\\')

text = text.replace('`', r'\`')

text = text.replace('*', r'\*')

text = text.replace('_', r'\_')

text = text.replace('{', r'\{')

text = text.replace('}', r'\}')

text = text.replace('[', r'\[')

text = text.replace(']', r'\]')

text = text.replace('(', r'\(')

text = text.replace(')', r'\)')

text = text.replace('>', r'\>')

text = text.replace('#', r'\#')

text = text.replace('+', r'\+')

text = text.replace('-', r'\-')

text = text.replace('.', r'\.')

text = text.replace('!', r'\!')

text = text.replace('$', r'\$')

def i(text):

text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

这是相同输入字符串的结果abc&def#ghi:

a)100000个循环,最佳3:6.72μs/循环

b)100000个循环,最佳3:2.64μs/循环

c)100000个循环,最佳3:每循环11.9μs

d)100000个循环,最佳为每循环3:4.92μs

e)100000个循环,最佳3:每循环2.96μs

f)100000个循环,最佳3:每循环4.29μs

g)100000个循环,最佳3:4.68μs/循环

h)100000个循环,最佳3:每循环4.73μs

i)100000个循环,最佳3:每循环4.24μs

并使用更长的输入字符串(## *Something* and [another] thing in a longer sentence with {more} things to replace$):

a)100000个循环,最佳3:每循环7.59μs

b)100000个循环,最佳3:每循环6.54μs

c)100000个循环,最佳3:每循环16.9μs

d)100000个循环,最佳3:每循环7.29μs

e)100000个循环,最佳3:每循环12.2μs

f)100000个循环,最佳3:每循环5.38μs

g)10000个循环,最佳3:21.7μs/循环

h)100000个循环,最佳3:每循环5.7μs

i)100000个循环,最佳3:每循环5.13μs

添加几个变种:

def ab(text):

for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:

text = text.replace(ch,"\\"+ch)

def ba(text):

chars = "\\`*_{}[]()>#+-.!$"

for c in chars:

if c in text:

text = text.replace(c, "\\" + c)

输入时间较短:

ab)100000个循环,最佳3:每循环7.05μs

ba)100000个循环,最佳3:每循环2.4μs

输入时间越长:

ab)100000个循环,最佳3:每循环7.71μs

ba)100000个循环,最佳3:每循环6.08μs

所以我将ba用于可读性和速度。

附录

在评论中被haccks提示,ab和之间的区别ba是if c in text:支票。让我们针对另外两个变体测试它们:

def ab_with_check(text):

for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:

if ch in text:

text = text.replace(ch,"\\"+ch)

def ba_without_check(text):

chars = "\\`*_{}[]()>#+-.!$"

for c in chars:

text = text.replace(c, "\\" + c)

Python 2.7.14和3.6.3上的每个循环的时间以μs为单位,并且与之前设置的机器不同,因此无法直接进行比较。

╭────────────╥──────┬───────────────┬──────┬──────────────────╮

│ Py, input ║ ab │ ab_with_check │ ba │ ba_without_check │

╞════════════╬══════╪═══════════════╪══════╪══════════════════╡

│ Py2, short ║ 8.81 │ 4.22 │ 3.45 │ 8.01 │

│ Py3, short ║ 5.54 │ 1.34 │ 1.46 │ 5.34 │

├────────────╫──────┼───────────────┼──────┼──────────────────┤

│ Py2, long ║ 9.3 │ 7.15 │ 6.85 │ 8.55 │

│ Py3, long ║ 7.43 │ 4.38 │ 4.41 │ 7.02 │

└────────────╨──────┴───────────────┴──────┴──────────────────┘

我们可以得出结论:

支票的人比没有支票的人快4倍

ab_with_check在Python 3上稍微领先,但是ba(带有check)在Python 2上有更大的领先优势

然而,这里最大的教训是Python 3比Python 2快3倍!Python 3上最慢的和Python 2上的最快之间没有太大的区别!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值