Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中实现翻译功能?_Python_String_Replace_Translation - Fatal编程技术网

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

如何在python中实现翻译功能?,python,string,replace,translation,Python,String,Replace,Translation,我想问一些关于使用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): dict

我想问一些关于使用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
例如:

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

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

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

tweet
是什么类型的?
translate
是什么样子的?
tweet
是一个字符串,
translate
是我尝试使用的
string
中的一个函数。
translate
函数只是字符的一对一映射。因此,您可以用不同的字母替换单个字母。您可以检查此解决方案,但translate对于您的pupose是错误的函数。翻译的dict输入应该是字符的1对1映射。因此,您可以将a设置为1,但不能将amk设置为123,因为它包含多个字符。来源:
tweet
是什么类型的,
translate
是什么样子的?
tweet
是一个字符串,
translate
是我尝试使用的
string
中的一个函数。
translate
函数只是字符的一对一映射。因此,您可以用不同的字母替换单个字母。您可以检查此解决方案,但translate对于您的pupose是错误的函数。翻译的dict输入应该是字符的1对1映射。因此,您可以将a设置为1,但不能将amk设置为123,因为它包含多个字符。资料来源: