妹子是做翻译相关的,遇到个问题,要求得到句子中的所有单词的 音标;

有道翻译只能对单个单词翻译音标,不能对多个单词或者句子段落翻译音标;

手工一个一个翻的话那就要累死人了.....于是就让我写个翻译音标工具

一开始没想到该怎么搞,,之后突然想到了利用有道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;的更多相关文章

  1. 如何用python批量翻译文本?

    首先,看一下百度翻译的官方api文档. http://api.fanyi.baidu.com/api/trans/product/apidoc # coding=utf-8 #authority:bi ...

  2. 纯 Python 实现的 Google 批量翻译

    测试通过时间:2019-8-20 参阅:C#实现谷歌翻译API.Python之Google翻译爬虫 首先声明,没有什么不良动机,因为经常会用 translate.google.cn,就想着用 Pyth ...

  3. Python汉英/英汉翻译(百度API/有道API)

    一.百度API实现 Step1:申请API Key 以前用过BAE,已经有了Api Key,没有的可以去申请 Step2:挺简单,直接看实现的代码吧 ```python #coding:utf-8 i ...

  4. Python批量图片识别并翻译——我用python给女朋友翻译化妆品标签

    Python批量图片识别并翻译--我用python给女朋友翻译化妆品标签 最近小编遇到一个生存问题,女朋友让我给她翻译英文化妆品标签.美其名曰:"程序猿每天英语开发,英文一定很好吧,来帮我翻 ...

  5. Python反编译调用有道翻译(附完整代码)

         网易有道翻译是一款非常优秀的产品,他们的神经网络翻译真的挺无敌.无奈有道客户端实在是太难用了,而且在某些具体场景 (比如对网站进行批量翻译) 无法使用,而有道的云服务又特别的贵,一般人是无法 ...

  6. 使用python的Flask实现一个RESTful API服务器端[翻译]

    最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文将会使用python的Flask框架轻松实现一个RESTful的服务 ...

  7. 简单实现Python调用有道API接口(最新的)

    # ''' # Created on 2018-5-26 # # @author: yaoshuangqi # ''' import urllib.request import urllib.pars ...

  8. C# 有道API翻译 查询单词详细信息

    原文:C# 有道API翻译 查询单词详细信息 有道云官方文档 有道云翻译API简介:http://ai.youdao.com/docs/doc-trans-api.s#p01 有道云C#Demo : ...

  9. 使用python的Flask实现一个RESTful API服务器端

    使用python的Flask实现一个RESTful API服务器端 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文 ...

随机推荐

  1. ReactNative学习之Html基础

    前言: React Native开发作为一种新型的移动开发方式,个人觉得App的一部分需求会逐步替换成这种方式,也是公司移动开发人员所必须掌握的一种开发技术,所以鉴于这种情况我觉得很有必要学习一下,特 ...

  2. 每天一个JS 小demo之韩雪冬轮播图。主要知识点:html,css布局,对于数组和对象的理解和运用

    @charset "utf-8"; /* CSS Document */ ;; } li { list-style: none; } img { border: none; } b ...

  3. dotnet 命令实战

    以下用实例串起dotnet所有命令,带你玩转dotnet命令. 1.创建(dotnet new) 首先我们创建一个项目,这里我们创建控制台程序,命令如下图所示. dotnet new dotnet n ...

  4. Core ML 机器学习

    在WWDC 2017开发者大会上,苹果宣布了一系列新的面向开发者的机器学习 API,包括面部识别的视觉 API.自然语言处理 API,这些 API 集成了苹果所谓的 Core ML 框架.Core M ...

  5. Eclipse中如何显示代码行

    方法一 快捷键方式: 按住 Ctrl + F10 选择 show  Line Numbers 方法二 手动操作: Window -- Prefences -- General -- Editors - ...

  6. 用hmmlearn学习隐马尔科夫模型HMM

    在之前的HMM系列中,我们对隐马尔科夫模型HMM的原理以及三个问题的求解方法做了总结.本文我们就从实践的角度用Python的hmmlearn库来学习HMM的使用.关于hmmlearn的更多资料在官方文 ...

  7. cadence pcb 设计学习记录提纲

    Cadence软件是一款"一站式"的电气EDA软件系统.因能力所限,此处仅涉及使用cadence软件绘制PCB.日后随着对软件使用程度的加深,自己打算学习使用cadence软件的原 ...

  8. Bash中的数学计算

    一.整数计算 1.整数 $delare -i num$num=5+5$echo $num10 $num="5 + 8"$echo $num13注意:算式中如果有空格,需要用引号引起 ...

  9. 流畅的python学习笔记:第一章

    这一章中作者简要的介绍了python数据模型,主要是python的一些特殊方法.比如__len__, __getitem__. 并用一个纸牌的程序来讲解了这些方法 首先介绍下Tuple和nametup ...

  10. 有关Dom的一些操作

    学习前端的都会了解到一些Dom操作,让我们来看看Dom操作有哪些吧! DOM(即 Document Object Mode) 是 W3C(万维网联盟)的标准. DOM 定义了访问 HTML 和 XML ...