Python 批量翻译 使用有道api;
妹子是做翻译相关的,遇到个问题,要求得到句子中的所有单词的 音标;
有道翻译只能对单个单词翻译音标,不能对多个单词或者句子段落翻译音标;
手工一个一个翻的话那就要累死人了.....于是就让我写个翻译音标工具
一开始没想到该怎么搞,,之后突然想到了利用有道api网页翻译来做每个单词的音标翻译;
选择了python语言来写;也想过用C#或者c++来做,但是要用到curl库,解析json代码也麻烦;就直接用python写了;
有道翻译api网站: 需要申请key,直接替换 self.key = 'xxxx' self.keyfrom = 'xxxx' 就可以了
http://fanyi.youdao.com/openapi?path=data-mode
后来妹子说,他们有时候需要处理 字幕srt 文件的音标翻译,一句一句太慢了,
想直接读取srt,输出txt的工具;
下面上代码: 支持单行输入及输出:
# -*- coding: utf-8 -*-
import sys
import urllib2
import re
import json
import string
class Youdao:
def __init__(self):
self.url = 'http://fanyi.youdao.com/openapi.do'
self.key = '1106591478'
self.keyfrom = 'left69' def get_translation(self,words):
url = self.url + '?keyfrom=' + self.keyfrom + '&key='+self.key + '&type=data&doctype=json&version=1.1&q=' + words
result = urllib2.urlopen(url).read()
json_result = json.loads(result)
json_result = json_result["translation"]
for i in json_result:
print i youdao = Youdao()
def get_yinbiao(words):
splitStr = words
for c in string.punctuation:
if c != "'":
splitStr = splitStr.replace(c, ' ')
print " "+splitStr
listu = splitStr.split(' ')
output = ""
for j in listu:
output = output + ' ' + SendGet(j)
print output def SendGet(str):
judge = str.lower()
if judge.lower()=="it":
return "it"
if judge.lower()=="mr":
return "'miste(r)"
#print str
url = "http://fanyi.youdao.com/openapi.do?keyfrom=left69&key=1106591478&type=data&doctype=json&version=1.1&q="+str
req = urllib2.Request(url)
res_data = urllib2.urlopen(req)
res = res_data.read()
#print res
if(res == "no query"):
return judge
hjson = json.loads(res)
#print hjson['basic']['uk-phonetic']
#danci = hjson['basic']['uk-phonetic']
if(hjson['errorCode']!=0):
return judge
if hjson.has_key('basic'):
if hjson['basic'].has_key('uk-phonetic'):
danci=hjson['basic']['uk-phonetic']
else:
return judge
danci = danci.replace('[','')
danci = danci.replace(']','')
if danci.find(";") != -1:
listu = danci.split(';')
for j in listu:
if len(j)>0 :
return j
if danci.find(",") != -1:
listu = danci.split(',')
for j in listu:
if len(j)>0 :
return j
return danci
elif hjson.has_key('query'):
danci=hjson['query']
if danci.find(";") != -1:
listu = danci.split(';')
for j in listu:
return j
return danci
return judge
while True:
msg=raw_input("Enter input:")
if msg == 'quit':
break
get_yinbiao(msg)
#youdao.get_translation(msg)
上代码: 支持 srt格式的字幕
# -*- coding: utf-8 -*-
import sys
import urllib2
import re
import json
import string
import os import sys
reload(sys)
sys.setdefaultencoding( "utf-8" ) class Youdao:
def __init__(self):
self.url = 'http://fanyi.youdao.com/openapi.do'
self.key = '1106591478'
self.keyfrom = 'left69' def get_yinbiao(self,words):
splitStr = words
for c in string.punctuation:
if c != "'":
splitStr = splitStr.replace(c, ' ')
#print " "+splitStr
listu = splitStr.split(' ')
output = ""
for j in listu:
output = output + ' ' + self.SendGet(j)
return output def SendGet(self,str):
judge = str.lower()
if judge.lower()=="it":
return "it"
if judge.lower()=="mr":
return "'miste(r)"
#print str
url = "http://fanyi.youdao.com/openapi.do?keyfrom="+self.keyfrom+"Trans&key="+self.key+"&type=data&doctype=json&version=1.1&q="+str
req = urllib2.Request(url)
res_data = urllib2.urlopen(req)
res = res_data.read()
#print res
if(res == "no query"):
return judge
hjson = json.loads(res)
#print hjson['basic']['uk-phonetic']
#danci = hjson['basic']['uk-phonetic']
if(hjson['errorCode']!=0):
return judge
if hjson.has_key('basic'):
if hjson['basic'].has_key('uk-phonetic'):
danci=hjson['basic']['uk-phonetic']
else:
return judge
danci = danci.replace('[','') danci = danci.replace(']','')
if danci.find(";") != -1:
listu = danci.split(';')
for j in listu:
if len(j)>0 :
return j
if danci.find(",") != -1:
listu = danci.split(',')
for j in listu:
if len(j)>0 :
return j
return danci
elif hjson.has_key('query'):
danci=hjson['query']
if danci.find(";") != -1:
listu = danci.split(';')
for j in listu:
return j
return danci
return judge
youdao = Youdao()
srt_path = sys.path[0]
#print srt_path
os.chdir(srt_path)
FileNames = os.listdir(srt_path)
#print FileNames
#for d_file in FileNames:#
# if ('.txt' not in d_file and '.srt' not in d_file):
# continue
# print d_file
while True:
#file = open(d_file, 'r+','utf8')
d_file = raw_input("Enter file name:")
if d_file == 'q':
break
file = open(d_file, 'r+')
count = len(open(d_file, 'r+').readlines())
print count
w_file = d_file.split('.')[0] + "_out.txt"
#print w_file
Wfile = open(w_file,'w')
line = 0
pocess = 1
while 1:
line = line + 1
line2 = 1
data = file.readline()
if not data :
break
lines = line % 5
if lines == 3:
pp = pocess*500/count
ppp = '%d' %pp
pos = "Process:"+ppp + "%"
print pos
pocess = pocess+1
Wfile.write(data)
writedata=youdao.get_yinbiao(data)
Wfile.write(writedata+"\n")
if lines == 4:
Wfile.write(data+"\n")
Wfile.write("")
print "翻译 success!"
print " "
Wfile.close()
Python 批量翻译 使用有道api;的更多相关文章
- 如何用python批量翻译文本?
首先,看一下百度翻译的官方api文档. http://api.fanyi.baidu.com/api/trans/product/apidoc # coding=utf-8 #authority:bi ...
- 纯 Python 实现的 Google 批量翻译
测试通过时间:2019-8-20 参阅:C#实现谷歌翻译API.Python之Google翻译爬虫 首先声明,没有什么不良动机,因为经常会用 translate.google.cn,就想着用 Pyth ...
- Python汉英/英汉翻译(百度API/有道API)
一.百度API实现 Step1:申请API Key 以前用过BAE,已经有了Api Key,没有的可以去申请 Step2:挺简单,直接看实现的代码吧 ```python #coding:utf-8 i ...
- Python批量图片识别并翻译——我用python给女朋友翻译化妆品标签
Python批量图片识别并翻译--我用python给女朋友翻译化妆品标签 最近小编遇到一个生存问题,女朋友让我给她翻译英文化妆品标签.美其名曰:"程序猿每天英语开发,英文一定很好吧,来帮我翻 ...
- Python反编译调用有道翻译(附完整代码)
网易有道翻译是一款非常优秀的产品,他们的神经网络翻译真的挺无敌.无奈有道客户端实在是太难用了,而且在某些具体场景 (比如对网站进行批量翻译) 无法使用,而有道的云服务又特别的贵,一般人是无法 ...
- 使用python的Flask实现一个RESTful API服务器端[翻译]
最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文将会使用python的Flask框架轻松实现一个RESTful的服务 ...
- 简单实现Python调用有道API接口(最新的)
# ''' # Created on 2018-5-26 # # @author: yaoshuangqi # ''' import urllib.request import urllib.pars ...
- C# 有道API翻译 查询单词详细信息
原文:C# 有道API翻译 查询单词详细信息 有道云官方文档 有道云翻译API简介:http://ai.youdao.com/docs/doc-trans-api.s#p01 有道云C#Demo : ...
- 使用python的Flask实现一个RESTful API服务器端
使用python的Flask实现一个RESTful API服务器端 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文 ...
随机推荐
- jquery+js实现鼠标位移放大镜效果
jQuery实现仿某东商品详情页放大镜效果 用jquery+js实现放大镜效果,效果大概如下图! 效果是不是大家很感兴趣,放大镜查看细节,下边大家可以详细看一看具体是怎么实现的.下边直接看代码! HT ...
- Sql的连接表补充
连接条件可在FROM或WHERE子句中指定,建议在FROM子句中指定连接条件.WHERE和HAVING子句也可以包含搜索条件,以进一步筛选连接条件所选的行. 连接可分为 ...
- python语言精粹《一》
第一章 静态语言:需要声明类型.变量不能改变类型! 动态语言:(也称脚本语言)主要的应用场景都是很短的应用程序(脚本),比如给静态语言编写的程序进行数据预处理.这样的程序通常也统称胶水代码. pyth ...
- Spring的<context:property-placeholder.../>在junit中不起作用,失效,解决方法
大家都知道,我们使用spring框架的时候喜欢把可以配置的变量放入一个properties配置文件中,然后在spring的applicationContext.xml配置文件中加入配置: <co ...
- lucene全文搜索之三:生成索引字段,创建索引文档(给索引字段加权)基于lucene5.5.3
前言:上一章中我们已经实现了索引器的创建,但是我们没有索引文档,本章将会讲解如何生成字段.创建索引文档,给字段加权以及保存文档到索引器目录 luncene5.5.3集合jar包下载地址:http:// ...
- php面向对象3
类的定义 基本定义 class 类名{ 访问修饰符 成员属性; 访问修饰符 成员方法; } 说明: ①类一定要class关键词修饰 ②类名的规范说明,使用大驼峰法 ③php 中,类名不区分大小写.但是 ...
- Javascript中的数组去重-indexof方法
在Javascript中,有时我们会用到数组去重.我在这里给大家介绍一下本人认为最简单实用的一种方法-indexOf()去重. var arr = [1,1,1,2,2,2,3,3,4,5,6,2,1 ...
- js获取页面宽高
网页可见区域宽:document.body.clientWidth网页可见区域高:document.body.clientHeight网页可见区域宽:document.body.offsetWidth ...
- JavaScript面向对象轻松入门之封装(demo by ES5、ES6、TypeScript)
本章默认大家已经看过作者的前一篇文章 <JavaScript面向对象轻松入门之抽象> 为什么要封装? 封装(Encapsulation)就是把对象的内部属性和方法隐藏起来,外部代码访问该对 ...
- Kubernetes服务之StatefulSets简介
StatefulSets在v1.5时还是个beta特性,它取代了v1.4的PetSets特性.PetSets的用户可以参考v1.5的升级指导,将正在运行的PeetSets升级到StatefulSets ...