我需要将用户输入的字符串转换为摩斯电码。我们教授要求我们从morseCode.txt文件中读取字母和其对应的摩斯电码并将它们分别存储到两个列表中,然后将每个字母转换为摩斯电码(在有空格的地方插入一个换行符)。
我已经完成了开始部分。我读取了morseCode.txt文件并将字母分别存储在列表[A,B,... Z]中,将摩斯电码存储在列表['- - . . - -\n','. - . - . -\n'...]中。
由于我们还没有学习“集合”,因此无法使用它。那么我该如何逐个字母地处理输入的字符串并将其转换为摩斯电码呢?我有些困惑。这是我目前的代码(很少......)
编辑:已经完成程序!
我已经完成了开始部分。我读取了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()
for x in inputLetters
循环内部。这样,您就可以“接受”超出范围的字符,然后继续转换其余的所有字符。此外,您就不需要提前删除所有空格了。 - dash-tom-bang