Use Python Baidu Translation API to realize Turkish translation
Turkish is one of the most widely spoken languages in the world. We can use the Python programming language combined with Baidu Translation API to easily realize the Turkish translation function. This article will introduce how to use Python to write code to achieve Turkish translation by calling Baidu Translation API.
First of all, before using the Baidu Translation API, we need to apply for a developer account on the Baidu Translation Open Platform and create an application to obtain the API's App ID and key.
Next, we can use the following Python code example to implement the Turkish translation function:
import hashlib import random import requests import json def translate(text, from_lang, to_lang): app_id = 'your_app_id' # 替换为自己申请的App ID secret_key = 'your_secret_key' # 替换为自己申请的密钥 url = 'https://fanyi-api.baidu.com/api/trans/vip/translate' salt = random.randint(32768, 65536) sign = app_id + text + str(salt) + secret_key sign = hashlib.md5(sign.encode()).hexdigest() params = { 'q': text, 'from': from_lang, 'to': to_lang, 'appid': app_id, 'salt': str(salt), 'sign': sign } try: response = requests.get(url, params=params) if response.status_code == 200: result = json.loads(response.text) if 'trans_result' in result: return result['trans_result'][0]['dst'] except Exception as e: print(f"翻译失败:{e}") return None if __name__ == '__main__': text_to_translate = '你好,世界!' translated_text = translate(text_to_translate, 'zh', 'tr') print(f"原文:{text_to_translate}") print(f"翻译结果:{translated_text}")
It should be noted that your_app_id
and ## in the above code #your_secret_key needs to be replaced with the App ID and key you applied for.
if __name__ == '__main__': and output the translation results.
The above is the detailed content of Implementing Turkish translation using python Baidu translation API. For more information, please follow other related articles on the PHP Chinese website!