从字典映射替换字符串中的字符 [英] Replace characters in string from dictionary mapping

查看:139
本文介绍了从字典映射替换字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢python,所以原谅我,如果我缺少一个明显的内置函数。



我有一个字典映射我生成如下:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆