我遇到了用脚本替换普通字母到特殊字符以测试翻译系统的脚本的麻烦,这是一个示例(cha-mate是chá-mate,但将使用chã-mate/chã-máte和其他变体进行测试),但是没有创建这种变化,而是将所有相同的字符切换为仅一个特殊字母,这是它的打印内容:
chá-máte
chã-mãte
理论上应该印出以下内容:
cha-máte
cha-mãte
chá-mate
chã-mate
etc.
这是使用的代码和json:
def translation_tester(word):
esp_chars = {
'a': 'áã',}
#words = [word]
for esp_char in esp_chars:
if esp_char in word:
replacement_chars = esp_chars[esp_char]
for i in range(len(replacement_chars)):
print(word.replace(esp_char,replacement_chars[i]))
def main():
words = ['cha-mate']
for word in words:
translation_tester(word)
main()
无论如何,感谢您的帮助,在此先感谢您!
最佳答案
要处理任意数量的替换,您需要使用递归.这就是我做的.
intword = 'cha-mate'
esp_chars = {'a': 'áã'}
def wpermute(word,i=0):
for idx,c in enumerate(word[i:],i):
if c in esp_chars:
for s in esp_chars[c]:
newword = word[0:idx] + s + word[idx + 1:]
wpermute(newword,idx + 1)
if idx == len(word) -1:
print(word)
wpermute(intword)
它提供了9种不同的方式写入单词的输出.
chá-máte
chá-mãte
chá-mate
chã-máte
chã-mãte
chã-mate
cha-máte
cha-mãte
cha-mate