Python Baidu Translation API implements Malay translation
Malay is one of the official languages of the Southeast Asian countries Malaysia and Indonesia, and is also widely used in Singapore and other places. In daily communication and translation work, Malay needs to be converted into other languages, which requires the use of translation API. This article will introduce how to use Python Baidu Translation API to implement Malay translation.
First of all, we need to prepare some work:
Install Python dependency package: "requests" is a common package used to send HTTP requests. Run the following command in the terminal to install it:
pip install requests
Connect Next, we write Python code to implement Malay translation. The specific implementation is as follows:
import requests import hashlib import random import json # 设置API Key和Secret Key api_key = 'your_api_key' secret_key = 'your_secret_key' # 设置请求参数 url = 'https://fanyi-api.baidu.com/api/trans/vip/translate' query = input('请输入要翻译的马来语句子:') from_lang = 'ms' to_lang = 'zh' salt = random.randint(32768, 65536) # 生成签名 sign = api_key + query + str(salt) + secret_key md5 = hashlib.md5() md5.update(sign.encode('utf-8')) sign = md5.hexdigest() # 发送请求 params = { 'q': query, 'from': from_lang, 'to': to_lang, 'appid': api_key, 'salt': salt, 'sign': sign, } response = requests.get(url, params=params) result = json.loads(response.text) # 解析并输出结果 print(f"翻译结果为:{result['trans_result'][0]['dst']}")
Run the above code, the program will ask the user to enter a Malay sentence. It will then call the Baidu Translation API to translate Malay to Chinese and output the results to the terminal.
In the code, we first set the API Key and Secret Key. Then, the request parameters are set, including url, query statement, source language and target language, salt (used for random number generation) and signature (parameters are combined for MD5 encryption). Finally, by sending a GET request and parsing the returned JSON data, we obtain the translated results and output them.
It should be noted that the API Key and Secret Key in this code need to be replaced with the keys you generated when you created the application on the Baidu Translation Open Platform.
Summary:
This article uses Python to write a simple Malay translation program, which implements the translation function from Malay to Chinese by calling Baidu Translation API. Through this example, we can use Python and Baidu Translation API to achieve translation needs between more languages. Hope this article is helpful to you!
The above is the detailed content of Python Baidu Translation API implements Malay translation. For more information, please follow other related articles on the PHP Chinese website!