2016-12-04 73 views
0

该函数将字典作为参数并翻译给定的字符串。然而,它已成为一个无限循环。我不能为了我的生活而弄清楚如何使它正常工作。例如:它应该是一个字符串“喜”,并将其翻译成“[ - ] 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

'new =''.join([glyphs.get(i,i)for input_string.split()])'? – Skycc

+0

您可能想要阅读[问]和[mcve]。 – boardrider

+0

@boardrider感谢您的提示! – Sakizzle

回答

0

看起来像你的字典包含可能的翻译列表作为值,你从中做出随机选择,和大写键。这个列表理解应该有效,然后:

import random 

new = ' '.join(random.choice(glyphs[word]) \ 
       for word in input_string.upper().split()) 
+0

我如何迭代字符串中的每个字符而不是单词?字典中的键用“1”代替“H”,“ - ”和“I” – Sakizzle