赞
踩
中英互译函数:
- def translate_english_to_chinese(text):
- """英文翻译为中文."""
- app_key = "xxxxx" # 有道翻译App Key
- app_secret = "xxxxxxx" # 有道翻译App Secret
- base_url = "https://openapi.youdao.com/api"
- app_id = "xxxxxxxx" # 有道翻译App ID
- from_lang = "en"
- to_lang = "zh-CHS"
- salt = str(random.randint(1, 65536))
- sign_str = app_id + text + salt + app_secret
- sign = hashlib.md5(sign_str.encode()).hexdigest()
- params = {
- "q": text,
- "from": from_lang,
- "to": to_lang,
- "appKey": app_key,
- "salt": salt,
- "sign": sign,
- }
- for the_num in range(5):
- try:
- response = req.post(base_url, data=params)
- result = response.json()
- if "translation" in result:
- return result["translation"][0]
- else:
- print("Translation Error:", result.get("errorMessage", "Unknown error"))
- time.sleep(the_num)
- except Exception as exception:
- print("Translation Error:", exception)
- time.sleep(the_num)
- return ''
'运行
调用函数:
- if __name__ == '__main__':
- # content = ''
- # for the_content in content_list:
- # content = f'{content}{translate_english_to_chinese(the_content)}'
- # time.sleep(0.02)
- word = 'i like apple'
- new_result = translate(word)
- print(new_result)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。