【发布时间】:2011-02-07 16:51:52
【问题描述】:
我需要将用户输入的字符串转换为莫尔斯电码。我们的教授希望我们这样做的方式是从 morseCode.txt 文件中读取,将 morseCode 中的字母分成两个列表,然后将每个字母转换为莫尔斯电码(当有空格时插入新行)。
我有一个开始。它所做的是读取 morseCode.txt 文件并将字母分成列表 [A, B, ... Z] 并将代码分成列表 ['– – 。 . - -\n','。 – 。 – 。 –\n'...]。
我们还没有学过“集合”,所以我不能用它。然后我将如何获取他们输入的字符串,逐个字母地遍历并将其转换为莫尔斯电码?我有点赶上。这是我现在拥有的(一点也不多……)
编辑:完成程序!
# open morseCode.txt file to read
morseCodeFile = open('morseCode.txt', 'r') # format is <letter>:<morse code translation><\n>
# create an empty list for letters
letterList = []
# create an empty list for morse codes
codeList = []
# read the first line of the morseCode.txt
line = morseCodeFile.readline()
# while the line is not empty
while line != '':
# strip the \n from the end of each line
line = line.rstrip()
# append the first character of the line to the letterList
letterList.append(line[0])
# append the 3rd to last character of the line to the codeList
codeList.append(line[2:])
# read the next line
line = morseCodeFile.readline()
# close the file
morseCodeFile.close()
try:
# get user input
print("Enter a string to convert to morse code or press <enter> to quit")
userInput = input("")
# while the user inputs something, continue
while userInput:
# strip the spaces from their input
userInput = userInput.replace(' ', '')
# convert to uppercase
userInput = userInput.upper()
# set string accumulator
accumulateLetters = ''
# go through each letter of the word
for x in userInput:
# get the index of the letterList using x
index = letterList.index(x)
# get the morse code value from the codeList using the index found above
value = codeList[index]
# accumulate the letter found above
accumulateLetters += value
# print the letters
print(accumulateLetters)
# input to try again or <enter> to quit
print("Try again or press <enter> to quit")
userInput = input("")
except ValueError:
print("Error in input. Only alphanumeric characters, a comma, and period allowed")
main()
【问题讨论】:
-
我知道您的老师会鼓励您对代码进行评论,但您也应该学习仅在他们添加有用的东西时使用它们;-)(例如文档 API,参考您的公式或数据表的位置取自,解释为什么在似乎有另一种更简单的情况下以某种方式做某事等)
-
考虑将 try/except 内容放在
for x in inputLetters循环中。这样,您可以“接受”超出范围的字符,然后继续转换所有其余字符。此外,您不需要删除前面的所有空格。 -
感谢 cmets 的各位。 dash-tom-bang,我通过附加列表来编辑程序以允许空格。感谢fortran,但不幸的是老师让我们编写程序的方式,她希望我们先用所有伪代码编写它,然后再回去用实际代码填充它。所以如果没有评论,她会知道我们没有先做伪代码。不过,我感谢你们所有人的帮助!
标签: python