2016-11-08 241 views
-1

我正在嘗試構建一個應用程序,它接受來自用戶的輸入並對其進行編碼並將其顯示回用戶輸入中的user.every字母應該由輸出中的另一個字母替換。這與字典的鍵/值一起使用。在我的代碼中,只能使用一個字母,如果再輸入一個字母,那麼它會打破。任何想法都將不勝感激,能夠在輸入中鍵入一個單詞,並在輸出中打印出相反的字母作爲單詞。python的字典鍵/值

def getInput(): 

    userInput = input("Enter String to encode: ") 
    return userInput 

def displayOutput(userInput, encoding): 

    matchFound = False 
    for key in encoding: 
     if (key == userInput): 
      print("Encoded message", encoding[key]) 
      matchFound = True 
      break 


    if matchFound == False: 
     print("***Error*** No Match Found!") 

def main(): 

    encoding ={"a": "b", "b": "c", "c": "d", "d": "e", "e": "f", "f": "g", "g": "h", "h": "i", "i": "j", "j": "k", "k": "l", "l": "m", "m": "n", "n": "o", "o": "p", "p": "q", "q": "r", "r": "s", "s": "t", "t": "u", "u": "v", "v": "w", "w": "x", "x": "y", "y": "z", "z": "a", " ": "-"} 


    userInput = getInput() 
    displayOutput(userInput, encoding) 


main() 
+1

你能更詳細的不是 「它打破」? –

+0

您需要遍歷輸入字符串中的字符。 – molbdnilo

+0

另外,爲什麼不'如果編碼user_input,並避免'編碼循環密鑰? –

回答

0

如果我正確理解您的要求,以下方法可以爲您工作。嘗試編碼,如果沒有值條目,則處理不存在編碼找到的情況。

def encode(s, encoding): 
    try: 
     return ''.join(encoding[character] for character in s) 
    except KeyError: 
     print "Encoding not found." 

樣本輸出:

>>> encoding = {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f", "f": "g", "g": "h", "h": "i", "i": "j", "j": "k", "k": "l", "l": "m", "m": "n", "n": "o", "o": "p", "p": "q", "q": "r", "r": "s", "s": "t", "t": "u", "u": "v", "v": "w", "w": "x", "x": "y", "y": "z", "z": "a", " ": "-"} 
>>> encode("helloworld", encoding)  
ifmmpxpsme 
>>> encode("HelloWorld", encoding) 
Encoding not found. 
+0

感謝您的幫助。我非常感謝它:) – nigelp12345

0

你正在比較你的編碼元素到整個userInput;你需要分別處理它的每個字符。

+0

這正是我想弄明白的,我不知道如何去做 – nigelp12345

+0

你知道嗎如何訪問'userInput'的每個字符? –

+0

不幸的是我沒有。你有沒有例子? – nigelp12345

0

而不是將整個輸入字符串與編碼鍵進行比較,您應該遍歷userInput字符串的字符。喜歡的東西:

encodedString = "" 

for inputChar in userInput: 
    if (inputChar in encoding): 
     encodedChar = encoding[inputChar] 
     encodedString = encodedString + encoding[inputChar] 
    else: 
     encodedString = encodedString + inputChar 

(未測試......剛剛輸入了我的頭頂部,所以可能不會實際運行。)

此解決方案假定您要輸出字符串(encodedString)和對於不在編碼中的字符,您只需使用輸入字符。不知道這是你真正想要或不是。

編輯:如果你希望它只適用於編碼中的輸入字符,那麼mrdomoboto的解決方案更高效且更緊湊。

+0

在Python標記的問題中,看起來大概是Java的東西,有趣的選擇。 – ospahiu

+0

是的,抱歉...修正了現在我的想法。 –