473,408 Members | 2,477 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Enter morse, exit ascii value?

Thekid
145 100+
I'm trying to figure out how to have a text file with a word in morse code in it and have my program decode it and print it out. I've managed to do the opposite where a word is in the text file and it's morse equivalent is printed out. I'm using a dictionary for the key:value of the morse, then I'm reversing the order and have a 'for' loop to run through the dict, and an 'if' statement to check the text file, then compare them.
If I enter this in the text file: -... .- --.
I'd like the program to print out:
b a d

Expand|Select|Wrap|Line Numbers
  1. # I've shortened the dict{} for this example
  2. # data.txt will contain morse code such as .- which is just the letter 'a'
  3. f = open("data.txt","r")
  4. text = f.read()
  5.  
  6. morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
  7. # reversing the order of the keys and values
  8. reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
  9. #check key and value, then comparing to data. If found, just print the value
  10. for k, v in reverse_morse.iteritems():
  11.      for item in text:
  12.           if item in k:
  13.             print v
  14.  
  15.  
The loop is reading each dot and dash in data.txt as seperate items so
if it it contains '.-' which is the letter 'a', instead it looks through
the dictionary for anything containing '.' and/or '-' so it would actually print each letter in morsedict twice, except for 'e', just once since it doesn't contain a dash but does a dot.
Jan 27 '10 #1

✓ answered by bvdet

Instead of iterating on the dictionary, iterate on the split string. Try this code:
Expand|Select|Wrap|Line Numbers
  1. text = "-... .- --. ....."
  2.  
  3. morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
  4. # reversing the order of the keys and values
  5. reverse_morse = dict([(code, letter) for (letter, code) in morsedict.items()])
  6.  
  7. print "".join([reverse_morse.get(letter, '') for letter in text.split()])
I modified your code for reverse_morse to use a list comprehension because I am in Python 2.3.

9 3195
Glenton
391 Expert 256MB
What you want to do is split your text by space and read it in a chunk at a time. This sounds like a job for the split command!

I've taken your code and added in line 6 and edited line 7:

Expand|Select|Wrap|Line Numbers
  1. morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
  2. # reversing the order of the keys and values
  3. reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
  4. #check key and value, then comparing to data. If found, just print the value
  5. for k, v in reverse_morse.iteritems():
  6.     text2=text.split(" ") 
  7.     for item in text2:
  8.           if item in k:
  9.             print v
This seems like a strange way of doing it. It's going to print out the letters contained in your text string. But if that's what you want...

If you want to do the more natural translation then it would be like this:
Expand|Select|Wrap|Line Numbers
  1. text2=text.split(" ")
  2. for t in text2:
  3.     print reverse_morse[t],
  4.  
Hope this helps...
Jan 27 '10 #2
bvdet
2,851 Expert Mod 2GB
Following is an another way of printing the decoded word:
Expand|Select|Wrap|Line Numbers
  1. print "".join([reverse_morse.get(letter, '') for letter in text.split()])
Jan 27 '10 #3
Thekid
145 100+
Thank you both for you replies! Glenton, the second suggestion of yours (the more natural translation) works better than my 'if item in k' loop but will print out each letter about 30 times like this: b a d b a d b ad b a d
Bvdet, your print suggestion works and removes the space between the letters but also prints numerous times like this:
bad
bad
bad
bad
bad

How do I get around this so they only print once? If I add in this print line to check it:
text = f.read()
print text
It shows the morse in data.txt: -... .- -..
Then I added it under this line to check and got this:
text2=text.split(" ")
print text2
output of about 34 lines:
['-...', '.-', '-..']
['-...', '.-', '-..']
['-...', '.-', '-..']
['-...', '.-', '-..']
['-...', '.-', '-..']
['-...', '.-', '-..']

Any suggestions or other adjustments I can make to my code? Thanks again!
*** I had changed the morse code for letter 'd' because I noticed I had it the same as
the letter 'g', in case anyone tries to get 'bad' they will actually get 'bag' unless that's corrected.
Jan 28 '10 #4
bvdet
2,851 Expert Mod 2GB
Instead of iterating on the dictionary, iterate on the split string. Try this code:
Expand|Select|Wrap|Line Numbers
  1. text = "-... .- --. ....."
  2.  
  3. morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
  4. # reversing the order of the keys and values
  5. reverse_morse = dict([(code, letter) for (letter, code) in morsedict.items()])
  6.  
  7. print "".join([reverse_morse.get(letter, '') for letter in text.split()])
I modified your code for reverse_morse to use a list comprehension because I am in Python 2.3.
Jan 28 '10 #5
bartonc
6,596 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. # Just as you would need to hear the pauses between letters being sent,
  2. # parsing morse will require some kind of separator.
  3. # I'm using two spaces between words here, but it could be anything
  4. # One spaces separates each letter in each word
  5. DEBUG = False
  6. text = ".-  -... .- --.  -.-. .- -..."  # "a bad cab"
  7.  
  8. morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
  9. # reversing the order of the keys and values
  10. reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
  11. if DEBUG:
  12.     print reverse_morse
  13. #check key and value, then comparing to data. If found, just print the value
  14. def decode(someMorseText):
  15.     decodedWords = []
  16.     morseWords = text.split("  ")   # two spaces
  17.     if DEBUG:
  18.         print morseWords
  19.     for morseWord in morseWords:
  20.         # broken down for simplicity's sake
  21.         morseLetters = morseWord.split(" ") # one space
  22.         if DEBUG:
  23.             print morseLetters
  24.         decodedWord = "".join([reverse_morse[val] for val in morseLetters])
  25.         decodedWords.append(decodedWord)
  26.     return " ".join(decodedWords)
  27.  
  28.  
  29.  
  30.  
  31. print decode(text)
Jan 28 '10 #6
bvdet
2,851 Expert Mod 2GB
Is it really you Barton? Where have you been hiding? It's been kinda lonesome around here.
Jan 28 '10 #7
Glenton
391 Expert 256MB
So what exactly does your text look like? It seems strange that text.split(" ") would create multiple lists as you suggest.

Also what output are you looking for? Do you not want to see repetitions?
Jan 28 '10 #8
Thekid
145 100+
Thanks again for all the replies, here's the final:

Expand|Select|Wrap|Line Numbers
  1. f = open("data.txt","r")
  2. text = f.read()
  3.  
  4. morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.'}
  5. reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
  6. print "".join([reverse_morse.get(letter, '') for letter in text.split()])
  7.  
Jan 28 '10 #9
bvdet
2,851 Expert Mod 2GB
One thing you might do is change the null string for an odd character (example '$') in the dict.get() method. That way you will be able to see if an entry in the file is invalid instead of skipping it.
Jan 29 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Steve Horsley | last post by:
How can I get the ASCII value of a character, e.g. I have: str = "A B" for index in range(0, len(str)): value = WHAT_GOES_HERE?(str) print value and I hope to get: 65
6
by: Haas | last post by:
Hello folks, I just started a C++ course. An exercise is to give the ASCII value of a character read from keyboard. I place the input from the keyboard in a char-variable. How can i get the...
1
by: James Dean | last post by:
i want to be able to get the correct ascii value from a byte without having to use the Convert.ToChar function as a char takes up two bytes of space and it is affecting the performance of my...
5
by: Ken Varn | last post by:
If I have a value type such as int that I want to protect in a multi-threaded situation, Is it safe to use Monitor::Enter(__box(value))? I am thinking that a different object pointer is generated...
1
by: RAGHAVENDRAS | last post by:
Hi All, I am writing a script for getting the ASCII value for the keyboard input. The script: #!c:\perl\bin -w # sascii - Show ASCII values for keypresses use Term::ReadKey;...
2
saranjegan
by: saranjegan | last post by:
Dudes, this is my doubt i need to rename a file,i can make it thru rename function..but the modified name should be an original name added with ascii value of 23.. these are questions...
1
by: ssetz | last post by:
Hello, For work, I need to write a password filter. The problem is that my C+ + experience is only some practice in school, 10 years ago. I now develop in C# which is completely different to me....
4
by: divyac | last post by:
How to get the ascii value of enter key using javascript events?
5
by: sam177401 | last post by:
I need a program in which a single textbox and a button is there when we enter a text in textbox and press ok button. It should pick the value and post if it is a ascii value. Otherwise it will...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.