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

时间:2010-04-13 23:41:51

标签: python

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

我有一个开始。它的作用是读取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()   

8 个答案:

答案 0 :(得分:14)

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

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"

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分:2)

使用'index'。

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

当然,你需要验证你的输入字母(根据需要转换它的情况,首先通过检查索引来确保它在列表中!= -1),但这应该让你顺利

答案 4 :(得分:2)

我不能把这个问题留在这个状态,问题的最终代码悬在我身上......

dan:这是一个更整洁,更短的代码版本。这将是一个好主意,看看这是如何完成的,并在未来以这种方式编写代码。我意识到你可能不再需要这个代码了,但是学习如何做到这一点是一个好主意。有些事情需要注意:

  • 只有两条评论 - 即使第二条评论对熟悉Python的人来说也不是必需的,他们会意识到NL正在被剥夺。只有在增加价值的地方写评论。

  • with语句(在另一个答案中推荐)消除了通过上下文处理程序关闭文件的麻烦。

  • 使用字典而不是两个列表。

  • 生成器理解((x for y in z))用于在一行中进行翻译。

  • 尽可能少地在try / except块中包装代码,以减少捕获您不想要的异常的可能性。

  • 首先使用input()参数而不是print() - 使用'\n'获取所需的新行。

  • 不要为了它而跨多行或使用像这样的中间变量编写代码:

    a = a.b()
    a = a.c()
    b = a.x()
    c = b.y()
    

    相反,编写这样的结构,将调用链接为完全有效:

    a = a.b().c()
    c = a.x().y()
    

code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")

答案 5 :(得分:1)

# Open the file
f = open('morseCode.txt', 'r')

# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
    if not Line.strip(): break
    letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
    letters.append((letter.lower(), code))
f.close()

# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ") 

# Convert the codes to morse code
out = []
for c in i:
    found = False
    for letter, code in letters:
        if letter == c.lower():
            found = True
            out.append(code)
            break

    if not found: 
        raise Exception('invalid character: %s' % c)

# Print the output
print ' '.join(out)

答案 6 :(得分:1)

对于实际处理,我会保留一串成品,然后遍历他们输入的字符串中的每个字母。我会调用一个函数将一个字母转换为莫尔斯代码,然后将其添加到现有的莫尔斯代码字符串中。

finishedProduct = []
userInput = input("Enter text")
for letter in userInput:
    finishedProduct.append( letterToMorseCode(letter) )
theString = ''.join(finishedProduct)
print(theString)

您可以检查循环中的空间,也可以检查被调用的函数。

答案 7 :(得分:1)

首先创建一个查找表:

morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
    morse[ord(line[0].lower()) - ord('a')] = line[2:]

然后使用表转换:

for ch in userInput:
    print morse[ord(ch.lower()) - ord('a')]