[英]String translate using dict
我想使用由dict
创建的字典,用其他字符替换字符向量中的字母,如下所示
import string
trans1 = str.maketrans("abc","cda")
trans = dict(zip("abc","cda"))
out1 = "abcabc".translate(trans1)
out = "abcabc".translate(trans)
print(out1)
print(out)
所需的输出是"cdacda"
我得到的是
cdacda
abcabc
现在out1
是此所需的输出,但out
不是。 我不知道为什么会这样。 如何使用在translate
功能中通过字典创建的dict
? 那么,如果我想与trans
一起使用translate
,该怎么办?
我认为translate
方法不会接受字典对象。 此外,您应该查看所创建的内容:
>>> dict(zip("abc","cda"))
{'c': 'a', 'a': 'c', 'b': 'd'}
我认为那不是您想要的。 zip
将第一个和第二个参数中对应索引的元素配对。
您可以编写解决方法:
def translate_from_dict(original_text,dictionary_of_translations):
out = original_text
for target in dictionary_of_translations:
trans = str.maketrans(target,dictionary_of_translations[target])
out = out.translate(trans)
return out
trans = {"abc":"cda"}
out = translate_from_dict("abcabc",trans)
print(out)
使用dict
函数创建字典。 阅读函数定义 。
>>> dict([("abc","cda")])
{"abc":"cda"}
str.translate
完全支持str.translate
(实际上,它支持任何支持索引的内容,即__getitem__
)–只是键必须是字符的序数表示,而不是字符本身。
相比:
>>> "abc".translate({"a": "d"})
'abc'
>>> "abc".translate({ord("a"): "d"})
'dbc'
string.translate
不支持使用字典作为参数:
translate(s, table, deletions='')
translate(s,table [,deletions]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings.
因此,您必须编写自己的函数。
另外,修改您的代码,因为它不会在我知道的任何python版本中运行。 它至少有2个例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.