GVKun编程网logo

python中的大量字符串替换?(python字符串替换多个字符)

22

如果您对python中的大量字符串替换?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于python中的大量字符串替换?的详细内容,我们还将为您解答python字符串替换多个

如果您对python中的大量字符串替换?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于python中的大量字符串替换?的详细内容,我们还将为您解答python字符串替换多个字符的相关问题,并且为您提供关于php – 在Python中执行多个字符串替换的最快实现、python – 如何用下一个字符串替换字符串中的字符?、python – 错误的字符串替换版本、python 字符串替换的有价值信息。

本文目录一览:

python中的大量字符串替换?(python字符串替换多个字符)

python中的大量字符串替换?(python字符串替换多个字符)

说我有一个看起来像这样的字符串:

str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"

您会注意到字符串中有很多与符号的位置,后跟一个字符(例如“&y”和“&c”)。我需要用字典中的适当值替换这些字符,如下所示:

dict = {"&y":"\033[0;30m",        "&c":"\033[0;31m",        "&b":"\033[0;32m",        "&Y":"\033[0;33m",        "&u":"\033[0;34m"}

最快的方法是什么?我可以手动找到所有“&”号,然后遍历字典以更改它们,但这似乎很慢。进行一堆正则表达式替换似乎也很慢(我的实际代码中将有大约30-40对字典)。

任何建议表示赞赏,谢谢。

编辑:

正如在该问题的注释中所指出的那样,我的字典是在运行时之前定义的,并且在应用程序生命周期的过程中永远不会改变。它是ANSI转义序列的列表,其中将包含约40个项目。我要比较的平均字符串长度约为500个字符,但是会有不超过5000个字符的字符串(尽管很少见)。我目前也在使用Python
2.6。

编辑#2 我接受了Tor Valamos的回答是正确的,因为它不仅提供了有效的解决方案(尽管它不是 最佳
解决方案),而且考虑了所有其他问题,并且做了大量工作来比较所有这些问题。该答案是我在StackOverflow上遇到的最好,最有用的答案之一。恭喜您。

答案1

小编典典

mydict = {“&y”:”\033[0;30m”,
“&c”:”\033[0;31m”,
“&b”:”\033[0;32m”,
“&Y”:”\033[0;33m”,
“&u”:”\033[0;34m”}
mystr = “The &yquick &cbrown &bfox &Yjumps over the &ulazy dog”

for k, v in mydict.iteritems():    mystr = mystr.replace(k, v)print mystrThe ←[0;30mquick ←[0;31mbrown ←[0;32mfox ←[0;33mjumps over the ←[0;34mlazy dog

我比较了一些解决方案:

mydict = dict([(''&'' + chr(i), str(i)) for i in list(range(65, 91)) + list(range(97, 123))])# random inserts between keysfrom random import randintrawstr = ''''.join(mydict.keys())mystr = ''''for i in range(0, len(rawstr), 2):    mystr += chr(randint(65,91)) * randint(0,20) # insert between 0 and 20 charsfrom time import time# How many times to run each solutionrep = 10000print ''Running %d times with string length %d and '' \      ''random inserts of lengths 0-20'' % (rep, len(mystr))# My solutiont = time()for x in range(rep):    for k, v in mydict.items():        mystr.replace(k, v)    #print(mystr)print ''%-30s'' % ''Tor fixed & variable dict'', time()-tfrom re import sub, compile, escape# Peter Hansent = time()for x in range(rep):    sub(r''(&[a-zA-Z])'', r''%(\1)s'', mystr) % mydictprint ''%-30s'' % ''Peter fixed & variable dict'', time()-t# Claudiudef multiple_replace(dict, text):     # Create a regular expression  from the dictionary keys    regex = compile("(%s)" % "|".join(map(escape, dict.keys())))    # For each match, look-up corresponding value in dictionary    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)t = time()for x in range(rep):    multiple_replace(mydict, mystr)print ''%-30s'' % ''Claudio variable dict'', time()-t# Claudiu - Precompiledregex = compile("(%s)" % "|".join(map(escape, mydict.keys())))t = time()for x in range(rep):    regex.sub(lambda mo: mydict[mo.string[mo.start():mo.end()]], mystr)print ''%-30s'' % ''Claudio fixed dict'', time()-t# Andrew Y - variable dictdef mysubst(somestr, somedict):  subs = somestr.split("&")  return subs[0] + "".join(map(lambda arg: somedict["&" + arg[0:1]] + arg[1:], subs[1:]))t = time()for x in range(rep):    mysubst(mystr, mydict)print ''%-30s'' % ''Andrew Y variable dict'', time()-t# Andrew Y - fixeddef repl(s):  return mydict["&"+s[0:1]] + s[1:]t = time()for x in range(rep):    subs = mystr.split("&")    res = subs[0] + "".join(map(repl, subs[1:]))print ''%-30s'' % ''Andrew Y fixed dict'', time()-t

Python 2.6的结果

Running 10000 times with string length 490 and random inserts of lengths 0-20Tor fixed & variable dict      1.04699993134Peter fixed & variable dict    0.218999862671Claudio variable dict          2.48400020599Claudio fixed dict             0.0940001010895Andrew Y variable dict         0.0309998989105Andrew Y fixed dict            0.0310001373291

claudiu和andrew的解决方案都保持为0,因此我不得不将其增加到10000次运行。

我在 Python 3
(由于Unicode)中运行了它,将chars从39替换为1024(38是&符,所以我不想包含它)。字符串长度最大为10.000,包括大约980个替换字符串,长度为0-20的可变随机插入。从39到1024的unicode值会导致字符长度分别为1和2个字节,这可能会影响某些解决方案。

mydict = dict([(''&'' + chr(i), str(i)) for i in range(39,1024)])# random inserts between keysfrom random import randintrawstr = ''''.join(mydict.keys())mystr = ''''for i in range(0, len(rawstr), 2):    mystr += chr(randint(65,91)) * randint(0,20) # insert between 0 and 20 charsfrom time import time# How many times to run each solutionrep = 10000print(''Running %d times with string length %d and '' \      ''random inserts of lengths 0-20'' % (rep, len(mystr)))# Tor Valamo - too long#t = time()#for x in range(rep):#    for k, v in mydict.items():#        mystr.replace(k, v)#print(''%-30s'' % ''Tor fixed & variable dict'', time()-t)from re import sub, compile, escape# Peter Hansent = time()for x in range(rep):    sub(r''(&[a-zA-Z])'', r''%(\1)s'', mystr) % mydictprint(''%-30s'' % ''Peter fixed & variable dict'', time()-t)# Peter 2def dictsub(m):    return mydict[m.group()]t = time()for x in range(rep):    sub(r''(&[a-zA-Z])'', dictsub, mystr)print(''%-30s'' % ''Peter fixed dict'', time()-t)# Claudiu - too long#def multiple_replace(dict, text): #    # Create a regular expression  from the dictionary keys#    regex = compile("(%s)" % "|".join(map(escape, dict.keys())))##    # For each match, look-up corresponding value in dictionary#    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)##t = time()#for x in range(rep):#    multiple_replace(mydict, mystr)#print(''%-30s'' % ''Claudio variable dict'', time()-t)# Claudiu - Precompiledregex = compile("(%s)" % "|".join(map(escape, mydict.keys())))t = time()for x in range(rep):    regex.sub(lambda mo: mydict[mo.string[mo.start():mo.end()]], mystr)print(''%-30s'' % ''Claudio fixed dict'', time()-t)# Separate setup for Andrew and gnibbler optimized dictmydict = dict((k[1], v) for k, v in mydict.items())# Andrew Y - variable dictdef mysubst(somestr, somedict):  subs = somestr.split("&")  return subs[0] + "".join(map(lambda arg: somedict[arg[0:1]] + arg[1:], subs[1:]))def mysubst2(somestr, somedict):  subs = somestr.split("&")  return subs[0].join(map(lambda arg: somedict[arg[0:1]] + arg[1:], subs[1:]))t = time()for x in range(rep):    mysubst(mystr, mydict)print(''%-30s'' % ''Andrew Y variable dict'', time()-t)t = time()for x in range(rep):    mysubst2(mystr, mydict)print(''%-30s'' % ''Andrew Y variable dict 2'', time()-t)# Andrew Y - fixeddef repl(s):  return mydict[s[0:1]] + s[1:]t = time()for x in range(rep):    subs = mystr.split("&")    res = subs[0] + "".join(map(repl, subs[1:]))print(''%-30s'' % ''Andrew Y fixed dict'', time()-t)# gnibblert = time()for x in range(rep):    myparts = mystr.split("&")    myparts[1:]=[mydict[x[0]]+x[1:] for x in myparts[1:]]    "".join(myparts)print(''%-30s'' % ''gnibbler fixed & variable dict'', time()-t)

结果:

Running 10000 times with string length 9491 and random inserts of lengths 0-20Tor fixed & variable dict      0.0 # disqualified 329 secsPeter fixed & variable dict    2.07799983025Peter fixed dict               1.53100013733 Claudio variable dict          0.0 # disqualified, 37 secsClaudio fixed dict             1.5Andrew Y variable dict         0.578000068665Andrew Y variable dict 2       0.56299996376Andrew Y fixed dict            0.56200003624gnibbler fixed & variable dict 0.530999898911

(**请注意,gnibbler的代码使用了不同的字典,其中的键不包含’&’。Andrew的代码也使用了该备用字典,但并没有太大的区别,也许只是0.01倍的加速。)

php – 在Python中执行多个字符串替换的最快实现

php – 在Python中执行多个字符串替换的最快实现

除了对字符串进行“替换”链接(即text.replace(a,b).replace(c,d).replace(e,f)…)之外,是否有任何推荐的方法进行多个字符串替换?
例如,你如何实现一个快速的函数,其行为类似于 Python中的PHP的htmlspecialchars?

我比较了(1)多个’替换’方法,(2)正则表达式方法,和(3)马特安德森的方法.

n = 10次运行,结果如下:

在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个字符上:

TIME: 3 ms [ replace_method(str) ]
TIME: 7 ms [ regular_expression_method(str,dict) ]
TIME: 5 ms [ matts_multi_replace_method(list,str) ]

在100000个字符:

TIME: 36 ms [ replace_method(str) ]
TIME: 46 ms [ regular_expression_method(str,dict) ]
TIME: 39 ms [ matts_multi_replace_method(list,str) ]

在1000000个字符上:

TIME: 318 ms [ replace_method(str) ]
TIME: 360 ms [ regular_expression_method(str,dict) ]
TIME: 320 ms [ matts_multi_replace_method(list,str) ]

在3687809字符:

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在相当大的输入字符串上击败多’替换’方法感到荣幸.

任何人都有想法在较小的字符串上击败它吗?

可能会出现以下情况?使用要替换的第一个“from”项目将文本拆分为多个部分,然后递归地将每个部分拆分为子部分,并使用下一个“from”项目进行替换,依此类推,直到您访问了所有替换项目为止.然后在递归函数完成时为每个“to”替换项加入.

也许有点难以绕过下面的代码(这对我来说,我写了它),但似乎按预期运行.我没有对它进行基准测试,但我怀疑它会相当快.

def multi_replace(pairs,text):
    stack = list(pairs)
    stack.reverse()
    def replace(stack,parts):
        if not stack:
            return parts
        # copy the stack so I don't disturb parallel recursions
        stack = list(stack) 
        from_,to = stack.pop()
        #print 'split (%r=>%r)' % (from_,to),parts
        split_parts = [replace(stack,part.split(from_)) for part in parts]
        parts = [to.join(split_subparts) for split_subparts in split_parts]
        #print 'join (%r=>%r)' % (from_,parts
        return parts
    return replace(stack,[text])[0]


print multi_replace(
    [('foo','bar'),('baaz','foo'),('quux','moop')],'foobarbaazfooquuxquux')

对于:

barbarfoobarmoopmoop

python – 如何用下一个字符串替换字符串中的字符?

python – 如何用下一个字符串替换字符串中的字符?

我想用下一个字符替换字符串的每个字符,最后一个应该成为第一个.这是一个例子:

abcdefghijklmnopqrstuvwxyz

应成为:

bcdefghijklmnopqrstuvwxyza

是否可以在不使用替换功能的情况下进行26次?

解决方法

您可以使用 str.translate() method让Python在一个步骤中替换其他字符.

使用string.maketrans() function将ASCII字符映射到其目标;使用string.ascii_lowercase可以帮助您,因为它可以节省您自己键入所有字母:

from string import ascii_lowercase
try:
    # Python 2
    from string import maketrans
except ImportError:
    # Python 3 made maketrans a static method
    maketrans = str.maketrans 

cipher_map = maketrans(ascii_lowercase,ascii_lowercase[1:] + ascii_lowercase[:1])
encrypted = text.translate(cipher_map)

演示:

>>> from string import maketrans
>>> from string import ascii_lowercase
>>> cipher_map = maketrans(ascii_lowercase,ascii_lowercase[1:] + ascii_lowercase[:1])
>>> text = ''the quick brown fox jumped over the lazy dog''
>>> text.translate(cipher_map)
''uif rvjdl cspxo gpy kvnqfe pwfs uif mbaz eph''

python – 错误的字符串替换版本

python – 错误的字符串替换版本

参见英文答案 > Replacing multiple similar strings                                    1个
>             How to replace two things at once in a string?                                    6个
>             How to replace multiple substrings of a string?                                    19个
我陷入了一个非常直接的问题,但经过一些调整后,我根本找不到一个简单有效的算法来做到这一点.

所以基本上我有一个字符串,其中包含某些元素,例如:

l = "test %1,%13,%14,%15"

还有一张地图:

dict = {"%1": "%33","%13": "%14","%14","%15","%15": "%17"}

我想做以下的事情:

for k in dict.keys():
    l = l.replace(k,dict[k])

所以我期待的是:

l = "test %33,%15,%17"

但显然这是不可行的,因为键和值之间存在一些冲突.所以上面的代码会输出:

l = "test %33,%17,%17"

很抱歉这样的原生问题,但我该如何解决这个并得到我预期的输出?请注意,每个键/值的长度不固定,所以我不能做类似的事情:

m_idx = l_copy.find(key)
l = l[:m_idx] + dict[key] + l[m_idx+len(key):]

因为长度不固定,上面的代码仍然是错误的.

我清楚这个吗?任何建议将非常感激!

=======更新

因此所有键都遵循%[0-9]的这种模式.

解决方法

你可以使用带有lambda的re.sub:

import re
l = "test %1,%15"
_dict = {"%1": "%33","%14":"%15","%15": "%17"}
new_l = re.sub('%\d+',lambda x:_dict[x.group()],l)

输出:

'test %33,%17'

如果_dict中没有键,则可以使用dict.get通过提供默认值来防止KeyError:

new_l = re.sub('%\d+',lambda x:_dict.get(x.group(),x.group()),l)

python 字符串替换

python 字符串替换

python 字符串替换可以用2种方法实现:

1是用字符串本身的方法

>>> a = ''hello dave''
>>> a.replace(''dave'',''python'')
''hello python''

2用正则来替换字符串

>>> import re
>>> restr = re.compile(''python'')   如果编译,就用方法,如果不需要,可以使用函数
>>> b = restr.sub(''dave'',a)
>>> b
''hello dave''
sub() 用于完成搜索和代替功能,将某字符串中所有匹配正则表达式模式的部分进行替换.用来替换的部分通常是一个字符串,但也可能是一个函数,该函数返回一个用来替换的字符串.subn()和sub()一样,但它还返回一个表示替换次数的数字,替换后的字符串和表示替换次数的数字作为一个元组的元素返回.


关于python中的大量字符串替换?python字符串替换多个字符的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于php – 在Python中执行多个字符串替换的最快实现、python – 如何用下一个字符串替换字符串中的字符?、python – 错误的字符串替换版本、python 字符串替换的相关信息,请在本站寻找。

本文标签: