Python摩尔斯电码转换器中的KeyError

时间:2016-04-20 16:17:19

标签: python

我正在编写一个莫尔斯电码到文本/文本到Python 3中的莫尔斯电码程序,它似乎工作正常,直到我给它一个字母然后我得到以下错误:

Traceback (most recent call last):
  File "X:\GCU\CST-110\Week 5 Projects\Python Projects\Chapter 9 Exercise 21.py", line 79, in <module>
    print(words_to_morse(morse_dict))
  File "X:\GCU\CST-110\Week 5 Projects\Python Projects\Chapter 9 Exercise 21.py", line 45, in words_to_morse
    print(morse_dict[ch],end="")
KeyError: 'J'

我在哪里错过了这个问题?代码如下。谢谢你的帮助。

import string
def process_line(fileObj):
    morse_dict={}
    reverse_morse_dict={}
    for line in fileObj:
        line.strip()
        line=line.split()
        morse_dict[line[0]]=line[1]
        for key,value in list(morse_dict.items()):
            reverse_morse_dict[value]=key
            return morse_dict,reverse_morse_dict
def words_to_morse(morse_dict):
    words_str=input("\nEnter text to translate: ")
    words_str.strip()
    words_list=words_str.split()
    for word in words_list:
        for ch in word:
            if ch in string.ascii_letters:
                ch=ch.upper()
                print(morse_dict[ch],end="")
                if word!=words_list[-1]:
                    print("/",end="\n")
def morse_to_words(reverse_morse_dict):
    morse_str=input("\nEnter morse code to translate: ")
    print("")
    morse_str.strip()
    morse_str=morse_str.replace("/",".-.-..-.-.")
    morse_list=morse_str.split()
    words_list=[]
    for code in morse_list:
        words_list.append(reverse_morse_dict[code])
        lower_words_list=[]
        for ch in words_list:
            if ch in string.ascii_letters:
                ch=ch.lower()
                lower_words_list.append(ch)
            else:
                lower_words_list.append(ch)
                lower_words_str="".join(lower_words_list)
                lower_words_str=lower_words_str.replace("++","")
                print(lower_words_str)
fileObj=open("morse.txt","r")
morse_dict,reverse_morse_dict=process_line(fileObj)
print("\nHi, this program is used to translate text into morse code or translate morse code to text")
choice_str=input("\nEnter input translate code - 't' for text to morse code or 'm' for morse code to text: ")
choice_list=choice_str.split()
while True:
    if choice_list[0]=="t":
        print(words_to_morse(morse_dict))
        break
    if choice_list[0]=="m":
        print()
        print(morse_to_words(reverse_morse_dict))
        break
    else:
        print("\nThat is an invalid input command")
        choice_str=input("\nEnter input code again, 't' for text or 'm' for morse code: ")
        choice_list=choice_str.split()
        continue
print()
print("\nThanks for using Morse-text converter")

1 个答案:

答案 0 :(得分:0)

1)process_line()没有正确返回morse_dict,它是一个局部变量,将它返回到for循环之外,还

2)下面的部分不存储字符作为键,它将字存储为键

for line in fileObj:
    line.strip()
    line=line.split()