Python实现中英⽂翻译⽅法总结
Table of Contents
PYTHON 实现中英⽂⾃动翻译
代码下⽅有运⾏结果的是⾃⼰运⾏使⽤过了,其他的为参考链接内的源代码,备忘总结⽽已。如有需要,请⼤家按⽬录查阅,以免浪费时间。
有道翻译API,实现中英⽂翻译
每⼩时1000次访问限制,超过就会被禁封
import json
import requests
# 翻译函数,word 需要翻译的内容
def translate(word):
# 有道词典 api
url ='udao/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:
# 然后相应的结果
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 ='udao/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.)
#        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, 实现⽂献翻译及⽇常单词翻译
最新百度翻译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
python基础代码大全加翻译
myurl ='api.fanyi.baidu/api/trans/vip/translate'
q ='apple'# 要翻译的词
fromLang ='en'# 翻译源语⾔
toLang ='zh'# 译⽂语⾔
salt = random.randint(32768,65536)
# 签名
sign = appid+q+str(salt)+secretKey
m1 = md5()
m1.de(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"}]}
<class 'bytes'>
<class 'dict'>
苹果
# -*- coding: utf-8 -*-
"""
百度翻译api,先读⼊pdf的内容,再调⽤百度翻译的api来得到翻译后的内容
"""php加mysql购物网站源码
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*
verter import PDFPageAggregator
import os
import httplib
import md5
import urllib
import random
import json
import re
import sys
z型钢型号及重量表import sys
reload(sys)
sys.setdefaultencoding('utf8')
def translate_txt(paper):
appid ='*********'# 你的appid
secretKey ='*********'# 你的密钥
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 = w()
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')
# response是HTTPResponse对象
response = sponse()
web_code = ad()
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)
数据结构中sizeof什么意思# 创建⼀个PDF⽂档对象存储⽂档结构
document = PDFDocument(parser)
# 检查⽂件是否允许⽂本提取
if not document.is_extractable:
raise PDFTextExtractionNotAllowed
else:
# 创建⼀个PDF资源管理器对象来存储共赏资源
rsrcmgr = PDFResourceManager()
# 设定参数进⾏分析
laparams = LAParams()
# 创建⼀个PDF设备对象grep vim命令
# device=PDFDevice(rsrcmgr)
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
# 创建⼀个PDF解释器对象
interpreter = PDFPageInterpreter(rsrcmgr, device)
w3school手机软件# 处理每⼀页
for page ate_pages(document):
interpreter.process_page(page)
# 接受该页⾯的LTPage对象
layout = _result()
for x in layout:
for x in layout:
if(isinstance(x, LTTextBoxHorizontal)):
with open('','a')as f:
f._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
每天有1000个单词的翻译限制,不适合⼤量单词翻译
from translate import Translator
translator= Translator(to_lang="zh")
translation = anslate("Steelmaking")
print(translation)
炼钢
有道在线翻译模块:基于有道云翻译API的Python英汉互译模块
import pytranslator
youdao = udao('YOUR_KEY','YOU_KEY_FROM')

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。