I'm having some trouble in filtering a .txt file into sublists which I can then turn into a directory.
A sample from the text.txtA2.-B4-...C4-.-.D3-..E1.F4..-.G3--.H4....75--...85---..95----.05-----.6.-.-.-,6--..--?6..--..!5..--.
with no spaces or linebreaks, it's basically a line of text.
A2.- means that the symbol 'A' has 2 characters in morse-code, and they are .-, etc
What I would like to do is split this long string into sublists, that I can then zip together into a directory that I can then use to make a morse-code translator. What I would like the program to do: make a list keyList that contains the keys A,B,C,...,?,.,
and another list valueList that contains the values for the keys.
However since the keys are not all letters im having problems filtering through the entire file.
What I have tried:
import re
r = open("text.txt", "r")
ss = r.read()
p = re.compile('\w'+'\w')
keyList = p.findall(ss)
ValueList = p.split(ss)
print(keyList)
print(ValueList)
keyList = ['A2', 'B4', 'C4', 'D3',..., '75', '85', '95', '05']
ValueList = ['', '.-', '-...', '-.-.', '-..', space , !5..--.']
As seen the valuelist will not split correctly, because '\w'+'\w' will only match alpha-numerical characters.. I have tried changing the argument on re.compile but have not found anything that has worked. Any help? is re.compiled the best way to do this or is there another way to filter through the text?
EDIT: expected/wanted output:
keyList = ['A','B','C','D',...,'.','?',',']
ValueList = ['.-','-...','-.-.','-..',...,'.-.-.-','..--..','--..--']
To make an encoder/decoder, you probably want to use dictionaries rather than lists.
As far as parsing it, a direct naive approach is probably best here.
result = {}
with open('morse.txt', 'r') as f:
while True:
key = f.read(1)
length_str = f.read(1)
if len(key) != 1 or len(length_str) != 1:
break
try:
length = int(length_str)
except ValueError:
break
value = f.read(length)
if len(value) == length:
result[key] = value
for k, v in result.items():
print k, v
results in:
A .-
! ..--.
C -.-.
B -...
E .
D -..
G --.
F ..-.
H ....
, --..--
. .-.-.-
0 -----
7 --...
9 ----.
8 ---..
? ..--..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With