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的形式了. 本文 ...
随机推荐
- 堆结构的优秀实现类----PriorityQueue优先队列
之前的文章中,我们有介绍过动态数组ArrayList,双向队列LinkedList,键值对集合HashMap,树集TreeMap.他们都各自有各自的优点,ArrayList动态扩容,数组实现查询非常快 ...
- JavaSE教程-02Java基本语法-练习
请说出下面的运算结果及解释为什么 System.out.println(1+1+"1");//? System.out.println("1"+1+1);//? ...
- 关于redis内部的数据结构
最大感受,无论从设计还是源码,Redis都尽量做到简单,其中运用到的原理也通俗易懂.特别是源码,简洁易读,真正做到clean and clear, 这篇文章以unstable分支的源码为基准,先从大体 ...
- linux定时任务访问url
这次linux定时任务设置成功,也算是自己学习linux中一个小小的里程碑.:) 撒花撒花--- 以下操作均是在ubuntu 下操作的,亲测有效,其他的linux系统还望亲们自己去查.鞠躬感谢! 1 ...
- ASP.NET MVC5(四):数据注解和验证
前言 用户输入验证的工作,不仅要在客户端浏览器中执行,还要在服务端执行.主要原因是客户端验证会对输入数据给出即时反馈,提高用户体验:服务器端验证,主要是因为不能完全信任用户提供的数据.ASP.NET ...
- 深入理解PHP对象注入
0x00 背景 php对象注入是一个非常常见的漏洞,这个类型的漏洞虽然有些难以利用,但仍旧非常危险,为了理解这个漏洞,请读者具备基础的php知识. 0x01 漏洞案例 如果你觉得这是个渣渣洞,那么请看 ...
- vue2.0实现分页组件
最近使用vue2.0重构项目, 需要实现一个分页的表格, 没有找到合适的组件, 就自己写了一个, 效果如下: 该项目是使用 vue-cli搭建的, 如果你的项目中没有使用webpack,请根据代码自己 ...
- 玩转UITableView系列(一)--- 解耦封装、简化代码、适者生存!
UITableView这个iOS开发中永远绕不开的UIView,那么就不可避免的要在多个页面多种场景下反复摩擦UITableView,就算是刚跳进火坑不久的iOS Developer也知道实现UITa ...
- Mysql 根据时间戳按年月日分组统计
Mysql 根据时间戳按年月日分组统计create_time时间格式SELECT DATE_FORMAT(create_time,'%Y%u') weeks,COUNT(id) COUNT FROM ...
- windows环境下,怎么解决无法使用ping命令
基本都是因为"环境变量"导致的,查看环境变量path在"Path"中追加"C:\Windows\System32"