[英]String translate using dict
I want to replace letters in a character vector by other ones, using a dictionary created with dict
, as follows 我想使用由
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)
The desired output is "cdacda"
所需的输出是
"cdacda"
What I get is 我得到的是
cdacda
abcabc
Now out1
is this desired output, but out
is not. 现在
out1
是此所需的输出,但out
不是。 I can not figure out why this is the case. 我不知道为什么会这样。 How can I use the dictionary created via
dict
in the translate
function? 如何使用在
translate
功能中通过字典创建的dict
? So what do I have to change if I want to use translate
with trans
? 那么,如果我想与
trans
一起使用translate
,该怎么办?
I do not think the method translate
will accept a dictionary object. 我认为
translate
方法不会接受字典对象。 Aditionlly, you should look at what you are creating: 此外,您应该查看所创建的内容:
>>> dict(zip("abc","cda"))
{'c': 'a', 'a': 'c', 'b': 'd'}
I do not think that is what you wanted. 我认为那不是您想要的。
zip
pairs off correspondingly indexed elements from the first and second argument. zip
将第一个和第二个参数中对应索引的元素配对。
You could write a work around: 您可以编写解决方法:
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)
Usage of the dict
function to create the dictionary. 使用
dict
函数创建字典。 Read the function definition . 阅读函数定义 。
>>> dict([("abc","cda")])
{"abc":"cda"}
str.translate
supports dicts perfectly well (in fact, it supports anything that supports indexing, ie __getitem__
) – it's just that the key has to be the ordinal representation of the character, not the character itself. str.translate
完全支持str.translate
(实际上,它支持任何支持索引的内容,即__getitem__
)–只是键必须是字符的序数表示,而不是字符本身。
Compare: 相比:
>>> "abc".translate({"a": "d"})
'abc'
>>> "abc".translate({ord("a"): "d"})
'dbc'
The string.translate
doesn't support dictionaries as arguments: 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.
So, you have to write your own function. 因此,您必须编写自己的函数。
Also, revise your code as it wont run in any python version that I know. 另外,修改您的代码,因为它不会在我知道的任何python版本中运行。 It has at least 2 exceptions.
它至少有2个例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.