转换表值错误 ValueError: 转换表中的字符串键长度必须为 1

Bot*_*akk 2 python syntax-error

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import os, sys

test = input()
translation = {

    "hi":"jk" , "as":"bc" , "ca":"sa"
}

translated = test.maketrans(translation)
print(test.translate(translated))
Run Code Online (Sandbox Code Playgroud)

结果

Traceback (most recent call last):
  File "C:/Users/DELL/PycharmProjects/untitled1/Inpage.py", line 11, in <module>
    translated = test.maketrans(translation)
ValueError: string keys in translate table must be of length 1
Run Code Online (Sandbox Code Playgroud)

不要介意导入和神奇的评论。该程序与utf-8相关,对于当前的问题并不重要。任何人都有解决方法或某种方法来解决这个问题,我会很高兴。该表有 47 个翻译长度。

Nel*_*eva 5

不允许密钥长度大于 1 是有其意图的。例如,如果您有两个翻译键 - “ca”和“c”,哪一个优先?

我不知道你的具体用例,但假设你已经按照感兴趣的顺序订购了翻译地图(最常见的是我认为你会希望它按长度排序,从小到大)。

然后您可以执行以下操作:

import re

def custom_make_translation(text, translation):
    regex = re.compile('|'.join(map(re.escape, translation)))
    return regex.sub(lambda match: translation[match.group(0)], text)
Run Code Online (Sandbox Code Playgroud)

请注意,对于给定的实现,此

translation = {
    "hi":"jk", 
    "as":"bc", 
    "ca":"sa",
    "c": "oh no, this is not prioritized"
}

text = "hi this is as test ca"
translated = custom_make_translation(text, translation)
Run Code Online (Sandbox Code Playgroud)

将给出翻译的值"jk tjks is bc test sa"

但这会优先考虑“c”而不是“ca”,因为它在字典中较早

translation = {
    "hi":"jk", 
    "as":"bc",
    "c": "i have priority",
    "ca":"sa"
}

text = "hi this is as test ca"
translated = custom_make_translation(text, translation)
Run Code Online (Sandbox Code Playgroud)

将给出翻译的值"jk tjks is bc test i have prioritya"

因此请务必谨慎使用。

此外,在 for 循环中使用正则表达式而不是 .replace 可确保您立即进行所有替换。否则,如果您有文本"a"和翻译图:{"a": "ab", "ab": "abc"}翻译最终将是"abc"而不是"ab"