从字典映射替换字符串中的字符 [英] Replace characters in string from dictionary mapping
问题描述
我有一个字典映射我生成如下:
dictionary = dict(zip(restAlphaSet,list(item)))
其中restAlpha将其设置为字符串,列表(item)是列表转换迭代
我正在尝试使用它来替换字符串中的所有字符。我发现一个replaceAll在线功能如下所示:
def replace_all(text,dic):
for i ,j in dic.iteritems():
if i!= j:
text = text.replace(i,j)
return text
不幸的是,这是有缺陷的,好像映射有一个 - > b,b-> a,那么没有什么会改变,因为b将被改回
我发现了翻译功能,但它不接受字典输入。
翻译方式更快。</ p>
>>>导入字符串
>>> text.translate(string.maketrans(。join(restAlphaSet),。join(item)))
I'm pretty new to python, so forgive me if I am missing an obvious built-in function.
I have a dictionary mapping I generated like the following:
dictionary = dict(zip(restAlphaSet,list(item)))
where restAlphaSet it a string and list(item) is list converted iteration
I am trying to use this to replace all the characters in my string. I found a replaceAll function online that looks like the following:
def replace_all(text, dic):
for i, j in dic.iteritems():
if i != j:
text = text.replace(i, j)
return text
Unfortunately, this is flawed as if the mapping has a->b, b->a, then nothing would get changed as the b's would be changed back to the a's.
I found the translate function, but it doesn't accept a dictionary input.
Translations are way faster.
>>> import string
>>> text.translate(string.maketrans("".join(restAlphaSet),"".join(item)))
这篇关于从字典映射替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!