使用的方法

  1. #coding:utf-8
  2. import requests
  3. import string
  4. import time
  5. import hashlib
  6. import json
  7. from PyPDF2.pdf import PdfFileReader, PdfFileWriter, ContentStream
  8. #init
  9. api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate"
  10. my_appid = "你的appid"
  11. cyber = "你的appkey"
  12. ## 处理pdf
  13. def getDataUsingPyPdf(filename):
  14. pdf = PdfFileReader(open(filename, "rb"))
  15. content = ""
  16. num = pdf.getNumPages()
  17. for i in range(0, num):
  18. extractedText = pdf.getPage(i).extractText()
  19. content += extractedText + "\n"
  20. return content
  21. def translate(word):
  22. #init salt and final_sign
  23. salt = str(time.time())[:10]
  24. final_sign = str(my_appid)+word+salt+cyber
  25. final_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest()
  26. #其中form和to可以区别en,zh构造请求参数
  27. paramas = {
  28. 'q':word,
  29. 'from':'en',
  30. 'to':'zh',
  31. 'appid':'%s'%my_appid,
  32. 'salt':'%s'%salt,
  33. 'sign':'%s'%final_sign
  34. }
  35. my_url = api_url+'?appid='+str(my_appid)+'&q='+word+'&from='+'zh'+'&to='+'en'+'&salt='+salt+'&sign='+final_sign
  36. response = requests.get(api_url,params = paramas).content
  37. #content = str(response,encoding = "utf-8")
  38. content = str(response)
  39. print(content)
  40. json_reads = json.loads(content)
  41. return json_reads['trans_result'][0]['dst']+" "
  42. content = getDataUsingPyPdf("test.pdf")
  43. clist = content.split(".")
  44. i=0
  45. while(i<clist.__len__()):
  46. print(translate(clist[i].replace("\n"," ")))
  47. i+=1