How to read a string one letter at a time in python

I need to convert a string entered by a user into Morse code. The way our professor wants us to do this is to read the morseCode.txt file, separate the letters from morseCode to two lists, and then convert each letter to Morse code (inserting a new line when there is a space).

I have a beginning. What he does is read the morseCode.txt file and separate the letters in the list [A, B, ... Z] and the codes in the list ['- -., - - \ n', '. -. -. -.\P"...]

We have not studied the “sets” yet, so I cannot use this. How then will I take the line that they entered by going letter by letter and converting it to Morse code? I caught up a little. Here is what I have right now (not so much ...)

EDIT: program completed!

# 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() 
+4
source share
8 answers

Why not just loop over a string?

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

returns

 a b c d 

So, in pseudo-code, I would do the following:

 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) 

Note: morse_code_ify is a pseudo-code.

You definitely want to create a list of characters that you want to output, and not just concatenate them at the end of a line. As stated above, this is O (n ^ 2): bad. Just add them to the list and then use the "".join(the_list) .

As a note: why do you remove spaces? Why not just return morse_code_ify(" ") a "\n" ?

+9
source

A few things for ya:

Download will be "better":

 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 

This way you do not need to close, and you do not need to manually load each line, etc. etc.

 for letter in userInput: if ValidateLetter(letter): # you need to define this code = GetMorseCode(letter) # from my other answer # do whatever you want 
+4
source
 # 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) 
+2
source

Use 'index'.

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

Of course, you will want to check your input letter (if necessary, convert its case, make sure it is listed first by checking this index! = -1), but this should lead you to the next path.

+2
source

I cannot leave this question in this state with this final code in the question hanging over me ...

dan: here is a much tidier and shorter version of your code. It would be nice to take a look at how this is done, and even more code in the future. I understand that you probably no longer need this code, but learning how you should do this is a good idea. Some notes:

  • There are only two comments - and even the second one is not needed by someone familiar with Python, they will understand that NL is losing. Just write comments where it adds meaning.

  • The with statement (recommended in another answer) fixes the problem of closing a file with a context handler.

  • Use a dictionary instead of two lists.

  • To perform the translation in one line, the understanding of the generator ( (x for y in z) ) is used.

  • Wrap as little code as possible in the try / except block to reduce the chance of catching an exception that you did not want.

  • First, use the input() argument instead of print() ing - use '\n' to get the new line you want.

  • Do not write code over multiple lines or with intermediate variables, as is the case for it:

     a = ab() a = ac() b = ax() c = by() 

    Instead, write these constructs as follows: the call chain is absolutely true:

     a = ab().c() c = ax().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") 
+2
source
 # 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) 
+1
source

For the actual processing, I would save the line of the finished product and cite each letter in the line that they entered. I would call a function to convert a letter to Morse code, and then add it to a line of existing Morse code.

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

You can either check the space in the loop or in the called function.

+1
source

First create a lookup table:

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

Then convert using the table:

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

Source: https://habr.com/ru/post/1306865/


All Articles