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

dan*_*dan 11 python

我需要将用户输入的字符串转换为莫尔斯电码.我们教授希望我们这样做的方法是从morseCode.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()   
Run Code Online (Sandbox Code Playgroud)

mel*_*ort 15

为什么不迭代字符串?

a_string="abcd"
for letter in a_string:
    print letter
Run Code Online (Sandbox Code Playgroud)

回报

a
b
c
d
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

注意:该morse_code_ify函数是伪代码.

肯定想要列出你想要输出的字符,而不是在一些字符串的末尾连接它们.如上所述,它是O(n ^ 2):糟糕.只需将它们附加到列表中,然后使用即可"".join(the_list).

作为旁注:为什么要删除空格?为什么不morse_code_ify(" ")回来"\n"


mos*_*hez 2

# Retain a map of the Morse code
conversion = {}

# Read map from file, add it to the datastructure
morseCodeFile = file('morseCode.txt')
for line in moreCodeFile:
    conversion[line[0]] = line[2:]
morseCodeFile.close()

# Ask for input from the user
s = raw_input("Please enter string to translate")
# Go over each character, and print it the translation.
# Defensive programming: do something sane if the user 
# inputs non-Morse compatible strings.    
for c in s:
    print conversion.get(c, "No translation for "+c)
Run Code Online (Sandbox Code Playgroud)