Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a space between each word in the string

Tags:

python

I've been trying to make this more challenging for myself but I couldn't find a way to achieve this goal. So I wonder if its possible to separate words that have no space betweenThemLikeThisJustInASingleString Here's my code:

def translate_morse(string):
    morse_a = {
    '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':'--..',1:'.----',2:'..---',3:'...--',4:'....-',5:'.....',6:'-....',7:'--...',8:'---..',9:'----.',0:'-----'}
    translated = ""
    for i in string.split(' '):
        for key, value in morse_a.iteritems():
            if i == value:
                translated += key
    print translated

print """

    ###################################
    #                                 #
    #   Morse Alphabet Translator     #
    #   Author: Blackwolf             #
    #   Date: 2016-29-05              #
    #                                 #
    ###################################
    #                                 #
    #             USAGE:              #
    #  After each morse letter you    #
    #  will need to seperate (space)  #
    #  each letter                    #
    ###################################

"""
finished = False
while finished != True:
    translate_morse(raw_input("Enter morse: "))
    ask_ifFinished = raw_input('Are you done? (Y/N): ').lower()
    if ask_ifFinished == 'y':
        finished = True
like image 394
Feelsbadman Avatar asked Dec 22 '25 19:12

Feelsbadman


1 Answers

If you want to insert a space before every capital letter:

import re
string = 'betweenThemLikeThisJustInASingleString'
print(re.sub('([A-Z])', r' \1', string))

Output:

between Them Like This Just In A Single String

There's no perfect solution for splitting up words where the boundary isn't marked. How can the computer tell that singlestring should be split into single string and not sing lest ring (lest is an English word if you're not aware)? There are heuristics you could apply to make decent guesses but they're complicated and limited. You could also list all the possible solutions but that will also be difficult at your level.

like image 65
Alex Hall Avatar answered Dec 24 '25 07:12

Alex Hall