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

2024-05-16 05:02:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问一些关于使用python翻译somestring的问题。我有一个csv文件,包含类似这样的删节词典列表

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

我想将“before”列中包含单词的字符串转换为“after”列中的单词。我尝试使用这段代码,但它没有改变任何东西

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

例如:

  • 输入=“请输入您的测试结果”
  • 输出=“让我知道您的测试结果 结果请“

Tags: 文件csv列表dictionaryval单词tmpdict
1条回答
网友
1楼 · 发布于 2024-05-16 05:02:52

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

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

相关问题 更多 >