python百度翻译api
时间: 2025-01-04 10:15:11 浏览: 13
### 使用 Python 调用百度翻译 API
为了实现这一功能,首先需要安装 `requests` 库以便发送 HTTP 请求。可以通过 pip 安装该库:
```bash
pip install requests
```
下面是一个完整的例子展示如何利用 Python 来调用百度翻译 API 进行文本翻译[^2]。
#### 导入必要的模块并设置应用信息
```python
import hashlib
import random
import time
import requests
from urllib.parse import urlencode
app_id = 'your_app_id'
secret_key = 'your_secret_key'
def translate_text(text, from_lang='auto', to_lang='en'):
"""
Translate text using Baidu Translation API.
:param text: Text that needs translating.
:param from_lang: Source language code (default is auto).
:param to_lang: Target language code (default is English).
:return: Translated result as a string or None on failure.
"""
salt = str(random.randint(32768, 65536))
timestamp = str(int(time.time()))
sign_raw = app_id + text + salt + timestamp + secret_key
sign = hashlib.md5(sign_raw.encode('utf-8')).hexdigest()
```
#### 构建请求参数并向服务器发起 GET 请求
```python
params = {
'q': text,
'from': from_lang,
'to': to_lang,
'appid': app_id,
'salt': salt,
'timestamp': timestamp,
'sign': sign
}
url = f'https://fanyi-api.baidu.com/api/trans/vip/translate?{urlencode(params)}'
try:
response = requests.get(url)
if response.status_code == 200:
json_result = response.json()
translated_text = json_result['trans_result'][0]['dst']
return translated_text
else:
print(f"Error occurred while calling the translation API: {response.text}")
return None
except Exception as e:
print(e)
return None
```
此函数接受待翻译的文字以及源语言和目标语言作为输入参数,并返回已翻译的结果字符串。如果发生错误,则会打印相应的消息并将结果设为 `None`。
阅读全文