简体   繁体   中英

String translate using dict

I want to replace letters in a character vector by other ones, using a dictionary created with dict , as follows

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"

What I get is

cdacda
abcabc

Now out1 is this desired output, but out is not. I can not figure out why this is the case. How can I use the dictionary created via dict in the translate function? So what do I have to change if I want to use translate with trans ?

I do not think the method translate will accept a dictionary object. 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.

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. 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.

Compare:

>>> "abc".translate({"a": "d"})
'abc'
>>> "abc".translate({ord("a"): "d"})
'dbc'

The string.translate doesn't support dictionaries as arguments:

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. It has at least 2 exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM