my name is bishop
I am a python programmer
I am a writer
I practice zen meditation
I am a musician
I am in peak physical health
I am a photographer
I speak fluent russian


and I do not exist.........yet

Morse code translator

March 21st, 2008 by Robert

PythonI finally got around to whipping this up. It’s crude, but it’s a start. The next thing I need to do is fix the code tags for coldspell. They’re not behaving like good little tags should.

#Python morse code translator

morse_code = {'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':'----.',' ':' | '}

#Function to translate string to morse code

def translate(data):
    text = data.lower()
    #guardian code

    count = 0
    for i in text:
        print morse_code[text[count]] + '  ',
        count += 1

to_translate = raw_input("Type in the text that you would like
                             to translate into Morse code.  ")

translate(to_translate)

Posted in python |

4 Responses

  1. Yoshi Says:

    this is looking good. One thing though: why are you using the count variable? You see, the for loop iterates over the elements in an iterator. In your case, you are iterating over text. So, each iteration of the loop, the variable i (it is actually a variable) will contain next character of the text.

    allow me to demonstrate in the python interpreter:

    >>> for i in “abcdefgh”:
    … print i

    a
    b
    c
    d
    e
    f
    g
    h
    >>>

    of course, it makes more sense to name the variable something like char instead of i. The name is completely arbitrary. The point is, that i is there for a reason. The for loop should be read as such (pseudo code):

    for (each) item in iterator:
    do_stuff_with(item)

    in other words, your code doesn’t need a count variable to find the next character in the text. The variable i already contains the character:

    for i in text:
    print morse_code[i]

  2. Robert Says:

    Aha!! I see exactly what you mean. That’s the stuff that I seem to be missing when I code. Most of my code works, just not in the most efficient, elegant, or intelligent way.

    Awesome advice, thank you Yoshi. I’m going to repost this.

  3. Fred Says:

    You hae both the “A” and “W” characters as “.–” - “a” is “.-”

  4. Robert Says:

    Thanks Fred. I made the changes. Nice eye.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.