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

2024-04-26 08:05:30 发布

您现在位置: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 <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()   

Tags: ofthetotxtinputindexmorseline
3条回答

有几件事要告诉你:

这样加载会“更好”:

with file('morsecodes.txt', 'rt') as f:
   for line in f:
      line = line.strip()
      if len(line) > 0:
         # do your stuff to parse the file

这样就不需要关闭,也不需要手动加载每一行等

for letter in userInput:
   if ValidateLetter(letter):  # you need to define this
      code = GetMorseCode(letter)  # from my other answer
      # do whatever you want

为什么不遍历字符串呢?

a_string="abcd"
for letter in a_string:
    print letter

回报

a
b
c
d

所以,在伪ish代码中,我会这样做:

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函数是伪代码。

您肯定想将要输出的字符列成一个列表,而不是仅仅将它们连接到某个字符串的末尾。如上所述,它是O(n^2):坏的。只需将它们附加到列表中,然后使用"".join(the_list)

顺便说一句:你为什么要搬走这些地方?为什么不让morse_code_ify(" ")返回一个"\n"

使用“索引”。

def GetMorseCode(letter):
   index = letterList.index(letter)
   code = codeList[index]
   return code

当然,您需要验证您的输入字母(根据需要转换大小写,首先通过检查索引确保它在列表中!=—1),但这会让你走上正轨。

相关问题 更多 >