【问题标题】:How to make translating function in python?如何在python中制作翻译功能?
【发布时间】:2021-06-10 09:57:18
【问题描述】:

我想问一些关于使用 python 翻译 somestring 的问题。我有一个 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

例如:

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

【问题讨论】:

  • tweet 是什么类型,translate 长什么样子?
  • tweet 是一个字符串,translate 是我尝试使用的String 中的一个函数。
  • translate 函数只是字符的一对一映射。因此,您可以用不同的字母替换单个字母。您可以查看此stackoverflow.com/questions/25202007/… 以获得解决方案
  • 但是 translate 对您的目的来说是错误的功能。 translate 的 dict 输入应该是字符的一对一映射。因此,您可以将 a 设为 1,但不能将 amk 设为 123,因为它不止一个字符。来源:programiz.com/python-programming/methods/string/translate

标签: python string replace translation


【解决方案1】:

您可以将内容读取到 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

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2023-04-04
    • 2017-06-02
    • 1970-01-01
    • 2015-12-04
    • 2012-02-17
    相关资源
    最近更新 更多