Enter morse, exit ascii value?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thekid
    New Member
    • Feb 2007
    • 145

    Enter morse, exit ascii value?

    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

    Code:
    # I've shortened the dict{} for this example
    # data.txt will contain morse code such as .- which is just the letter 'a'
    f = open("data.txt","r")
    text = f.read()
    
    morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
    # reversing the order of the keys and values
    reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
    #check key and value, then comparing to data. If found, just print the value
    for k, v in reverse_morse.iteritems():
         for item in text:
              if item in k:
                print v
    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.
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    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:

    Code:
    morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
    # reversing the order of the keys and values
    reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
    #check key and value, then comparing to data. If found, just print the value
    for k, v in reverse_morse.iteritems():
        text2=text.split(" ") 
        for item in text2:
              if item in k:
                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:
    Code:
    text2=text.split(" ")
    for t in text2:
        print reverse_morse[t],
    Hope this helps...

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Following is an another way of printing the decoded word:
      Code:
      print "".join([reverse_morse.get(letter, '') for letter in text.split()])

      Comment

      • Thekid
        New Member
        • Feb 2007
        • 145

        #4
        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.spli t(" ")
        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.

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Instead of iterating on the dictionary, iterate on the split string. Try this code:
          Code:
          text = "-... .- --. ....."
           
          morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
          # reversing the order of the keys and values
          reverse_morse = dict([(code, letter) for (letter, code) in morsedict.items()])
          
          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.

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Code:
            # Just as you would need to hear the pauses between letters being sent,
            # parsing morse will require some kind of separator.
            # I'm using two spaces between words here, but it could be anything
            # One spaces separates each letter in each word
            DEBUG = False
            text = ".-  -... .- --.  -.-. .- -..."  # "a bad cab"
             
            morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'}
            # reversing the order of the keys and values
            reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
            if DEBUG:
                print reverse_morse
            #check key and value, then comparing to data. If found, just print the value
            def decode(someMorseText):
                decodedWords = []
                morseWords = text.split("  ")   # two spaces
                if DEBUG:
                    print morseWords
                for morseWord in morseWords:
                    # broken down for simplicity's sake
                    morseLetters = morseWord.split(" ") # one space
                    if DEBUG:
                        print morseLetters
                    decodedWord = "".join([reverse_morse[val] for val in morseLetters])
                    decodedWords.append(decodedWord)
                return " ".join(decodedWords)
                
            
            
            
            print decode(text)

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              Is it really you Barton? Where have you been hiding? It's been kinda lonesome around here.

              Comment

              • Glenton
                Recognized Expert Contributor
                • Nov 2008
                • 391

                #8
                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?

                Comment

                • Thekid
                  New Member
                  • Feb 2007
                  • 145

                  #9
                  Thanks again for all the replies, here's the final:

                  Code:
                  f = open("data.txt","r")
                  text = f.read()
                  
                  morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.'}
                  reverse_morse = dict((code, letter) for (letter, code) in morsedict.items())
                  print "".join([reverse_morse.get(letter, '') for letter in text.split()])

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    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.

                    Comment

                    Working...