使用 Microsoft 翻译服务将英文翻译成中文
Translating english to chinese using Microsoft translate service
我正在尝试使用微软翻译服务 (azure) 将一些英文文本翻译成中文,并为 python 请求库。
问题是我在接收翻译时输入了错误的字符。
我检查了响应编码,它是 utf-8,所以,这应该可以。
我使用这段代码进行翻译:
url = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en-US&to=zh-CN&textType=html"
headers = {
'Ocp-Apim-Subscription-Key': secretKey,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
body = [{
'text': string
}]
response = requests.post(url, headers=headers, json=body)
print(response.encoding) # This prints utf-8
response = request.json()
print(response[0]['translations'][0]['text'] # prints garbage
return response
这里可能发生了什么?
你得到的"garbage"是中文的,但它仍然是UTF-8编码,所以你必须把它当作一个原始字节串来解码。
以样本结果str
,
str = b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
print (str.decode('utf8'))
产量
你好吗?
发音为"Ni hao ma?",中文为"How do you do?"
我正在尝试使用微软翻译服务 (azure) 将一些英文文本翻译成中文,并为 python 请求库。
问题是我在接收翻译时输入了错误的字符。
我检查了响应编码,它是 utf-8,所以,这应该可以。
我使用这段代码进行翻译:
url = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en-US&to=zh-CN&textType=html"
headers = {
'Ocp-Apim-Subscription-Key': secretKey,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
body = [{
'text': string
}]
response = requests.post(url, headers=headers, json=body)
print(response.encoding) # This prints utf-8
response = request.json()
print(response[0]['translations'][0]['text'] # prints garbage
return response
这里可能发生了什么?
你得到的"garbage"是中文的,但它仍然是UTF-8编码,所以你必须把它当作一个原始字节串来解码。
以样本结果str
,
str = b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
print (str.decode('utf8'))
产量
你好吗?
发音为"Ni hao ma?",中文为"How do you do?"