此函数将字典作为参数并转换给定的字符串。然而,它已成为一个无限循环。我不能为我的生活弄清楚如何让它正常工作。例如:它应该采用字符串“hi”并将其转换为“[ - ] 1”
def translate(glyphs):
string = input("Enter string to be translated: ").strip()
new = ''
for keys in glyphs:
ind = string.upper().find(keys)
while ind != -1: #while there exists a key in the string
if len(glyphs[string[ind].upper()]) > 1: #if there is more than one value for key
rand = randint(0, 1) #choose randomly
transChar = glyphs[keys][rand]
new = string[:ind] + transChar + string[ind+1:]
ind = string.upper().find(keys)
print("hi1")
else:
transChar = glyphs[keys][0]
new = string[:ind] + transChar + string[ind+1:]
ind = string.upper().find(keys)
print("hi")
return new
任何帮助将不胜感激!
答案 0 :(得分:0)
您的字典看起来包含可能的翻译列表,您可以从中进行随机选择,以及大写字母键。这个列表理解应该有效,然后:
import random
new = ' '.join(random.choice(glyphs[word]) \
for word in input_string.upper().split())