I need to convert a string inputed by a user into morse code. The way our professor wants us to do this is to read from a morseCode.txt file, seperate the letters from the morseCode into two lists, then convert each letter to morse code (inserting a new line when there is a space).
I have the beginning. What it does is reads the morseCode.txt file and seperates the letters into a list [A, B, ... Z] and the codes into a list ['– – . . – –\n', '. – . – . –\n'...].
We haven't learned "sets" yet, so I can't use that. How would I then take the string that they inputed, go through letter by letter, and convert it to morse code? I'm a bit caught up. Here's what I have right now (not much at all...)
EDIT: completed the program!
# 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()