python怎么读中的字_如何在python中一次读一个字母的字符串

我需要把用户输入的字符串转换成莫尔斯电码。我们的教授希望我们这样做的方式是从一个morse code.txt文件中读取,将morseCode中的字母分成两个列表,然后将每个字母转换为morse代码(有空格时插入新行)。

我有开始。它所做的是读取morseCode.txt文件并将这些字母分成一个列表[a,B。。。Z] 把代码列成一个列表['–-。–––\n','。– . – . –\n'…]。

我们还没学会“套路”,所以我不能用它。那我怎么把他们输入的字符串,逐字逐句地读一遍,然后把它转换成莫尔斯电码呢?我有点忙。这是我现在所拥有的(一点也不多…)

编辑:完成程序!# open morseCode.txt file to read

morseCodeFile = open('morseCode.txt', 'r') # format is :

# 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 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 to quit

print("Try again or press to quit")

userInput = input("")

except ValueError:

print("Error in input. Only alphanumeric characters, a comma, and period allowed")

main()

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页