如何在Python中一个字母一个字母地读取字符串

13 投票
9 回答
162834 浏览
提问于 2025-04-15 21:34

我需要把用户输入的字符串转换成摩尔斯电码。我们的教授希望我们这样做:从一个叫做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()   

9 个回答

2

在编程中,有时候我们会遇到一些问题,想要找到解决办法。StackOverflow是一个很好的地方,大家可以在这里提问和回答问题。比如,有人可能会问如何解决某个错误,或者如何实现某个功能。其他人就会根据自己的经验来给出建议和解决方案。

在这个过程中,大家会分享代码示例,帮助理解。比如,可能会有一些代码块像

# 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)
这样的内容,里面包含了具体的代码,帮助你更好地理解问题和解决方案。

总之,StackOverflow是一个互相帮助的社区,大家可以在这里学习到很多编程知识,解决遇到的各种问题。

4

给你几点建议:

加载的方式可以改得“更好”一些,像这样:

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
21

为什么不直接遍历字符串呢?

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

返回

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

绝对应该先把想要输出的字符放到一个列表里,而不是直接把它们一个个加到某个字符串的末尾。正如上面提到的,这样做的效率是 O(n^2),很糟糕。你应该把它们添加到一个列表中,然后用 “”.join(the_list) 来合并。

顺便问一下:你为什么要去掉空格呢?为什么不让 morse_code_ify(" ") 返回一个 "\n" 呢?

撰写回答