当前位置:   article > 正文

调用百度API进行翻译

调用百度API进行翻译
  1. import re
  2. import requests
  3. import random
  4. import json
  5. from hashlib import md5
  6. from nltk import sent_tokenize
  7. class BaiduTranslator:
  8. def __init__(self, appid, appkey):
  9. self.appid = appid
  10. self.appkey = appkey
  11. self.endpoint = 'http://api.fanyi.baidu.com'
  12. self.path = '/api/trans/vip/translate'
  13. self.url = self.endpoint + self.path
  14. def translate(self, query, from_lang, to_lang):
  15. salt = random.randint(32768, 65536)
  16. sign = self.make_md5(self.appid + query + str(salt) + self.appkey)
  17. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  18. payload = {
  19. 'appid': self.appid,
  20. 'q': query,
  21. 'from': from_lang,
  22. 'to': to_lang,
  23. 'salt': salt,
  24. 'sign': sign
  25. }
  26. r = requests.post(self.url, params=payload, headers=headers)
  27. result = r.json()
  28. return result
  29. def make_md5(self, s, encoding='utf-8'):
  30. return md5(s.encode(encoding)).hexdigest()
  31. def split_sentences(self, text):
  32. sentences = re.split(r'[.;]', text)
  33. sentences = [s.strip() for s in sentences if s.strip()]
  34. return sentences
  35. def translate_text(self, text, from_lang, to_lang):
  36. sentences = self.split_sentences(text)
  37. translations = []
  38. for i, sentence in enumerate(sentences):
  39. result = self.translate(sentence, from_lang, to_lang)
  40. print(result)
  41. translations.append(result)
  42. print(f"原句{i+1}{sentence}")
  43. print(f"翻译结果{i+1}{result['trans_result'][0]['dst']}")
  44. return translations
  45. def translate_file(self, filename, from_lang, to_lang):
  46. with open(filename, 'r', encoding='utf-8') as file:
  47. text = file.read()
  48. return self.translate_text(text, from_lang, to_lang)
  49. # 示例用法
  50. appid = '2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  51. appkey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  52. translator = BaiduTranslator(appid, appkey)
  53. filename = '1.txt'
  54. from_lang = 'en'
  55. to_lang = 'zh'
  56. translations = translator.translate_file(filename, from_lang, to_lang)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/161865
推荐阅读
相关标签
  

闽ICP备14008679号