Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

small issue with whitespeace/punctuation in python?

I have this function that will convert text language into 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? it will return whyyoul8?. How would I go about separating the words when I return them, and how do I handle punctuation? Any help appreciated!

like image 257
snwflke00 Avatar asked Dec 20 '25 21:12

snwflke00


1 Answers

oneliner comprehension:

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

[Edit] Fixed regex.

like image 158
JBernardo Avatar answered Dec 22 '25 11:12

JBernardo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!