如何在python中实现翻译功能?

How to make translating function in python?

我想问一些关于使用 python 翻译一些字符串的问题。我有一个 csv 文件,其中包含这样的缩写字典列表。

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

我想将包含“之前”列中单词的字符串翻译为“之后”列中的单词。我尝试使用此代码,但它没有任何改变。

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

例如:

您可以将内容读入字典,然后使用以下代码。

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'))

输出

Shut the freak up and Let me know your test result please