Little problem with whitespeace / punctuation in python?

I have this function that converts a text language to English:

def translate(string):
    textDict={'y':'why', 'r':'are', "l8":'late', 'u':'you', 'gtg':'got to go',
        'lol': 'laugh out    loud', 'ur': 'your',}
    translatestring = ''
    for word in string.split(' '):
        if word in textDict:
            translatestring = translatestring + textDict[word]
        else:
            translatestring = translatestring + word
    return translatestring

However, if I want to translate y u l8?, he will return whyyoul8?. How would I like to separate words when I return them, and how can I process punctuation marks? Any help appreciated!

+3
source share
5 answers

oneliner:

''.join(textDict.get(word, word) for word in re.findall('\w+|\W+', string))

[Edit] Fixed regex.

+2
source

You add words to a string without spaces. If you are going to do it this way (instead of what was asked by your previous question on this topic), you will need to manually re-add spaces, since you will divide them into them.

0
source

"y u l8", ", [" y "," u "," l8 "]. [" "," "," "] - , " whyyoulate". if .

0

+ ' ' +, . , , :

import re

def translate_string(str):
    textDict={'y':'why', 'r':'are', "l8":'late', 'u':'you', 'gtg':'got to go',  'lol': 'laugh out loud', 'ur': 'your',}
    translatestring = ''
    for word in re.split('([^\w])*', str):
        if word in textDict:
            translatestring += textDict[word]
        else:
            translatestring += word

    return translatestring


print translate_string('y u l8?')

:

why you late?

, , , .

0

:

for word in string.split(' '):
    if word in textDict:
        translatestring = translatestring + textDict[word]
    else:
        translatestring = translatestring + word

string.split(''):   translateetring + = textDict.get(, )

dict.get(foo, default) foo default, foo .

(Start time, short notes now: when splitting, you can split based on punctuation as well as spaces, save punctuation or spaces and re-enter it when connected to the output line. This is a bit more work, but it will do the job.)

0
source

All Articles