Python实现中英文翻译方法总结

Table of Contents

  • 1  PYTHON 实现中英文自动翻译
    • 1.1  有道翻译API,实现中英文翻译
    • 1.2  百度翻译API, 实现文献翻译及日常单词翻译
    • 1.3  谷歌在线翻译模块:Google translate python
    • 1.4  有道在线翻译模块:基于有道云翻译API的Python英汉互译模块

PYTHON 实现中英文自动翻译

代码下方有运行结果的是自己运行使用过了,其他的为参考链接内的源代码,备忘总结而已。如有需要,请大家按目录查阅,以免浪费时间。

有道翻译API,实现中英文翻译

参考链接:https://segmentfault.com/a/1190000015643320

每小时1000次访问限制,超过就会被禁封!!!!

import json
import requests

# 翻译函数,word 需要翻译的内容
def translate(word):
    # 有道词典 api
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
    # 传输的参数,其中 i 为需要翻译的内容
    key = {
        'type': "AUTO",
        'i': word,
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "ue": "UTF-8",
        "action": "FY_BY_CLICKBUTTON",
        "typoResult": "true"
    }
    # key 这个字典为发送给有道词典服务器的内容
    response = requests.post(url, data=key)
    # 判断服务器是否相应成功
    if response.status_code == 200:
        # 然后相应的结果
        return response.text
    else:
        print("有道词典调用失败")
        # 相应失败就返回空
        return None

def get_reuslt(repsonse):
    # 通过 json.loads 把返回的结果加载成 json 格式
    result = json.loads(repsonse)
    print ("输入的词为:%s" % result['translateResult'][0][0]['src'])
    print ("翻译结果为:%s" % result['translateResult'][0][0]['tgt'])

def main():
    print("本程序调用有道词典的API进行翻译,可达到以下效果:")
    print("外文-->中文")
    print("中文-->英文")
    word = input('请输入你想要翻译的词或句:')
    list_trans = translate(word)
    get_reuslt(list_trans)

if __name__ == '__main__':
    main()
本程序调用有道词典的API进行翻译,可达到以下效果:
外文-->中文
中文-->英文
请输入你想要翻译的词或句:Apple
输入的词为:Apple
翻译结果为:苹果
"""有道翻译API的调用函数(封装为一个函数使用)"""
import json
import requests
import re

def translator(str):
    """
    input : str 需要翻译的字符串
    output:translation 翻译后的字符串
    """
    # API
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
    # 传输的参数, i为要翻译的内容
    key = {
        'type': "AUTO",
        'i': str,
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "ue": "UTF-8",
        "action": "FY_BY_CLICKBUTTON",
        "typoResult": "true"
    }
    # key 这个字典为发送给有道词典服务器的内容
    response = requests.post(url, data=key)
    # 判断服务器是否相应成功
    if response.status_code == 200:
        # 通过 json.loads 把返回的结果加载成 json 格式
        result = json.loads(response.text)
#         print ("输入的词为:%s" % result['translateResult'][0][0]['src'])
#         print ("翻译结果为:%s" % result['translateResult'][0][0]['tgt'])
        translation = result['translateResult'][0][0]['tgt']
        return translation
    else:
        print("有道词典调用失败")
        # 相应失败就返回空
        return None

"""有道翻译函数  DONE!"""
'有道翻译函数  DONE!'

百度翻译API, 实现文献翻译及日常单词翻译

参考文献:https://blog.csdn.net/baidu_33718858/article/details/83306851

最新百度翻译API收费标准:最近流水记录若当月翻译字符数≤2百万,当月免费;若超过2百万字符,按照49元/百万字符支付当月超出部分费用。

"""官方Python接入百度翻译API测试Demo(有所改动,官方DEMO有些过时,Python包有些变化)"""
import httplib2
import urllib
import random
import json
from hashlib import md5

appid = '*********' #你的appid
secretKey = '********' #你的密钥

 
httpClient = None
myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
q = 'apple'  # 要翻译的词
fromLang = 'en' # 翻译源语言
toLang = 'zh'  # 译文语言
salt = random.randint(32768, 65536)

# 签名
sign = appid+q+str(salt)+secretKey
m1 = md5()
m1.update(sign.encode(encoding = 'utf-8'))
sign = m1.hexdigest()
# myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
myurl = myurl+'?q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&appid='+appid+'&salt='+str(salt)+'&sign='+sign
try:
    h = httplib2.Http('.cache')
    response, content = h.request(myurl)
    if response.status == 200:
        print(content.decode('utf-8'))
        print(type(content))
        response = json.loads(content.decode('utf-8'))  # loads将json数据加载为dict格式
        print(type(response))
        print(response["trans_result"][0]['dst'])
except httplib2.ServerNotFoundError:
    print("Site is Down!")

{"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"\u82f9\u679c"}]}


苹果
# -*- coding: utf-8 -*-
"""
百度翻译api,先读入pdf的内容,再调用百度翻译的api来得到翻译后的内容
"""
 
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
from pdfminer.layout import *
from pdfminer.converter import PDFPageAggregator
import os
import httplib
import md5
import urllib
import random
import json
import re
 
import sys
reload(sys)
sys.setdefaultencoding('utf8')
 
def translate_txt(paper):
    appid = '20190523000301218'  # 你的appid
    secretKey = 'oOIMyO0qz212kecmB1mn'  # 你的密钥
 
    httpClient = None
    myurl = '/api/trans/vip/translate'
   
    q = paper
    # q = 'apple'
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint(32768, 65536)
 
    sign = appid + q + str(salt) + secretKey
    m1 = md5.new()
    m1.update(sign)
    sign = m1.hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
        salt) + '&sign=' + sign
 
    try:
        httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
 
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        web_code = response.read()
        param = json.loads(web_code, encoding='utf-8')
        print param['trans_result'][0]['dst']
        return param['trans_result'][0]['dst']
 
    except Exception, e:
        print e
    finally:
        if httpClient:
            httpClient.close()
 
 
def readpdf2txt(fp):
    # 来创建一个pdf文档分析器
    parser = PDFParser(fp)
    # 创建一个PDF文档对象存储文档结构
    document = PDFDocument(parser)
    # 检查文件是否允许文本提取
    if not document.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 创建一个PDF资源管理器对象来存储共赏资源
        rsrcmgr = PDFResourceManager()
        # 设定参数进行分析
        laparams = LAParams()
        # 创建一个PDF设备对象
        # device=PDFDevice(rsrcmgr)
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        # 创建一个PDF解释器对象
        interpreter = PDFPageInterpreter(rsrcmgr, device)
        # 处理每一页
        for page in PDFPage.create_pages(document):
            interpreter.process_page(page)
            # 接受该页面的LTPage对象
            layout = device.get_result()
            for x in layout:
                if (isinstance(x, LTTextBoxHorizontal)):
                    with open('output.txt', 'a') as f:
                        f.write(x.get_text())
                        # raw_paper = x.get_text()
                        # rel = translate_txt(raw_paper)
                        # f.write(str(rel) + '\n')
                        print 'lalala'
 
 
 
if __name__ == '__main__':
    '''''
     解析pdf 文本,保存到txt文件中
    '''
    print 'start'
    path = 'xx' # 文档的位置 
 
    pdfFile = open(path, 'rb')
    readpdf2txt(pdfFile)
    print 'done'
    pdfFile.close()

谷歌在线翻译模块:Google translate python

Reference: https://github.com/terryyin/translate-python

每天有1000个单词的翻译限制,不适合大量单词翻译

from translate import Translator
translator= Translator(to_lang="zh")
translation = translator.translate("Steelmaking")
print(translation)
炼钢

有道在线翻译模块:基于有道云翻译API的Python英汉互译模块

Reference: https://pypi.org/project/pytranslator/

import pytranslator
youdao = pytranslator.youdao('YOUR_KEY','YOU_KEY_FROM')
youdao.trans('help')

你可能感兴趣的:(个人总结)