So I am doing this challenge:
Question:
It’s 1868 and you’ve just bought a telegraph key so you can transmit messages in Morse code directly to your friend using a personal telegraph line. We’ve given you a file morsecode.txt which translates from any character (except a space) to its code. When a message is written in Morse code, characters are separated by spaces, while actual spaces are written as slash (/) in coded messages.
I want to split the input string into individual characters and verify it with the code in the file.
my code:
data = {} with open('morsecode.txt') as f: for line in f: key, value = line.split() data[key] = (value) code = input('Message: ').lower()
I can’t share the text file in stackoverflow for some reason
here’s the text in the file:
A .-
B -…
C -.-.
D -..
E .
F ..-.
G –.
H ….
I ..
J .—
K -.-
L .-..
M —
N -.
O —
P .–.
Q –.-
R .-.
S …
T –
U ..-
V …-
W .–
X -..-
Y -.–
Z –..
0 —–
1 .—-
2 ..—
3 …–
4 ….-
5 …..
6 -….
7 –…
8 —..
9 —-.
. .-.-.-
, –..–
? ..–..
- -….-
/ -..-.
: —…
‘ .—-.
- -….-
) -.–.-
; -.-.-
( -.–.
= -…-
@ .–.-.
Advertisement
Answer
Assuming data
dictionary is getting updated when you read from the text file, you can do the following:
code = input('Message: ').lower() new_string = ' '.join(data[letter] for letter in code)
.join
takes an iterable as an argument. You can fetch the particular value from the dictionary and pass them in join