I'm having trouble creating a function that uses a dictionary of texting abbreviations, and using the dictionary to write functions that translate to and from English. For example: “y r u l8?” translates to “Why are you late?” So I have this so far: (I don't need every single texting phrase)
def text(string):
textDict={'y':'why', "l8":'late','u':'you','gtg':'got t开发者_如何学运维o go', 'lol': 'laugh out loud', 'ur': 'your',}
any help is appreciated!
If you have a dictionary of replacements you can do this:
replacements = {
'lol': 'laugh out loud',
'y': 'why',
'l8': 'late',
'u': 'you',
'r': 'are'
}
s1 = 'y r u l8'
s2 = ' '.join([replacements.get(w, w) for w in s1.split()])
- string needs to be split into words
- then loop through each word and replace it with the one in the dictionary if found
- Then, reconstruct a new string from the words and return it.
str.split() splits into an array, array.join() joins it back.
This won't work if there is punctuation in the sentence. You would have to detect that and use the word without punctuation as the key
You could just split the text string and if its parts are in textDict and if they are replace them with the contents of the dictionary:
def translate(text_string, text_dict):
for word in text_string.split():
if word in text_dict:
text_string = text_string.replace(word, text_dict[word]
return text_string
For something a bit more elaborate try lookahead-lev. I made it for a similar situation. Just put your "thumblish" into a yaml file and call it. It's designed to be a web service, but you could probably modify it to suit your needs.
精彩评论