gpt4 book ai didi

python - 转换表值错误 ValueError : string keys in translate table must be of length 1

转载 作者:行者123 更新时间:2023-12-03 08:24:46 27 4
gpt4 key购买 nike

#!/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))

结果

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

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

最佳答案

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

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

然后您可以实现以下操作:

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)

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

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)

将给出翻译后的值“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)

将给出翻译后的值“jk tjks is bc test i haveprioritya”

所以请务必谨慎使用它。

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

关于python - 转换表值错误 ValueError : string keys in translate table must be of length 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63230213/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com