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的形式了. 本文 ...
随机推荐
- [HDU1002] A + B Problem II
Problem Description I have a very simple problem for you. Given two integers A and B, your job is to ...
- Go从入门到精通(一)go语言初始
一.第一个go程序 package main import ( "fmt" ) func main(){ fmt.Println("hello world") ...
- Redis 集群搭建详细指南
先有鸡还是先有蛋? 最近有朋友问了一个问题,说毕业后去大城市还是小城市?去大公司还是小公司?我的回答都是大城市!大公司! 为什么这么说呢,你想一下,无论女孩男孩找朋友都喜欢找个子高胸大的.同样的道理嘛 ...
- http服务器开发笔记(一)——先跑起来
做了很多年的web相关开发,从来也没有系统的学习http协议,最近正好工作不怎么忙,准备系统的学习一下. 接下来准备自己写一小型的http服务器来学习,因为现在对JavaScript比较熟悉,所以决定 ...
- html逻辑运算符
逻辑运算符 逻辑运算符用于测定变量或值之间的逻辑. 给定 x=6 以及 y=3,下表解释了逻辑运算符: &&and(x < 10 && y > 1) 为 t ...
- [css 实践篇] CSS box-orient
定义和用法 box-orient 属性规定框的子元素应该被水平或垂直排列. 提示:水平框中的子元素从左向右进行显示,而垂直框的子元素从上向下进行显示.不过,box-direction 和 box-or ...
- java递归算法实现 数字人民币大写转换
最近穷死了 ,没钱吃饭ing 写点钱给自己吧!public class Test{ public static String getChar(long a){ int b = (int)a; Map ...
- Winform Timer用法,Invoke在Timer的事件中更新控件状态
System.Timers.Timer可以定时执行方法,在指定的时间间隔之后执行事件. form窗体上放一个菜单,用于开始或者结束定时器Timer. 一个文本框,显示定时执行方法. public pa ...
- PHP设计模式:工厂方法
示例代码详见https://github.com/52fhy/design_patterns 工厂方法 工厂方法是针对每一种产品提供一个工厂类.通过不同的工厂实例来创建不同的产品实例. 相比简单工厂, ...
- nginx是什么nginx安装与配置之windows版
1.nginx是什么 为了快速了解nginx我们先引用网上的nginx介绍: Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP ...