我需要将用户输入的字符串转换为莫尔斯电码。我们的教授希望我们这样做的方法是从 morseCode.txt 文件中读取,将 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()
为什么不直接遍历字符串呢?
a_string="abcd"
for letter in a_string:
print letter
returns
a
b
c
d
所以,在伪代码中,我会这样做:
user_string = raw_input()
list_of_output = []
for letter in user_string:
list_of_output.append(morse_code_ify(letter))
output_string = "".join(list_of_output)
注:morse_code_ify
函数是伪代码。
You 确实想要制作一个要输出的字符列表,而不是仅仅将它们连接在某个字符串的末尾。如上所述,它的复杂度为 O(n^2):不好。只需将它们附加到列表中,然后使用"".join(the_list)
.
附带说明:为什么要删除空格?为什么不直接拥有morse_code_ify(" ")
返回一个"\n"
?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)