1

I want to ask something about translating somestring using python. I have a csv file contains list of abreviation dictionary like this.

before, after
ROFL, Rolling on floor laughing
STFU, Shut the freak up 
LMK, Let me know
...

I want to translate string that contains word in column "before" to be word in column "after". I try to use this code, but it doesn't change anything.

def replace_abbreviation(tweet): 

     dictionary = pd.read_csv("dict.csv", encoding='latin1') 
     dictionary['before'] = dictionary['before'].apply(lambda val: unicodedata.normalize('NFKD', val).encode('ascii', 'ignore').decode())

     tmp = dictionary.set_index('before').to_dict('split')
     tweet = tweet.translate(tmp)

     return tweet

For example :

  • Input = "lmk your test result please"
  • Output = "let me know your test result please"
Tiffany Arasya
  • 99
  • 1
  • 1
  • 9
  • What type is `tweet` and how does `translate` look like? – Brimbo Mar 12 '21 at 11:24
  • `tweet` is a string, and `translate` is a function in `String` that i try to use. – Tiffany Arasya Mar 12 '21 at 11:26
  • 2
    The `translate` function is only a one-to-one mapping for characters. So you can replace a single letter with a different letter. You can check this https://stackoverflow.com/questions/25202007/python-translate-with-multiple-characters for a solution – Brimbo Mar 12 '21 at 11:40
  • 1
    But translate is the wrong function for your pupose. The dict input for translate should be a 1-to-1 mapping of characters. So you can make a to 1, but not amk to 123 because its more than one character. source: https://www.programiz.com/python-programming/methods/string/translate – Doluk Mar 12 '21 at 11:40

1 Answers1

3

You can read the contents to a dict and then use the following code.

res = {}

with open('dict.csv') as file:
    next(file) # skip the first line "before, after"
    for line in file:
        k, v = line.strip().split(', ')
        res[k] = v

def replace(tweet):
    return ' '.join(res.get(x.upper(), x) for x in tweet.split())

print(replace('stfu and lmk your test result please'))

Output

Shut the freak up and Let me know your test result please
python_user
  • 5,375
  • 2
  • 13
  • 32