python自动翻译实现方法
作者:鹰眼 时间:2022-01-01 08:03:31
本文实例讲述了python自动翻译实现方法。分享给大家供大家参考,具体如下:
以前学过python的基础,一般也没用过。后来有一个参数表需要中英文。想了一下,还是用python做吧。调用的百度翻译接口,经历了乱码、模块不全等问题。一般google,一边做的。分享一下。
#encoding=utf-8
## eagle_91@sina.com
## created 2014-07-22
import urllib
import urllib2
import MySQLdb
import json
import gc
import time
url = 'http://openapi.baidu.com/public/2.0/bmt/translate'
_sleepTime = 0.5
_limit = 1000
## 链接mysql
conn = MySQLdb.connect(host='localhost',user='root',passwd='',charset='utf8')
curs = conn.cursor()
conn.select_db('test')
## 搜索要操作的表
count=curs.execute("""SELECT * FROM sb_parameters WHERE ISNULL(en_name) ORDER BY id ASC""")
## print curs.fetchall()
## print count
results = curs.fetchmany(_limit)
for r in results:
gc.collect()
chin = unicode(r[3]).encode('utf-8')
## print chin
values = {'client_id':'PWrGllvVAIFcD0sYqaipwkAV','q':chin,'from':'zh','to':'en'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
returnData = json.loads(the_page)
## print returnData
if returnData.has_key("error_code"):
continue;
inputData = returnData["trans_result"][0]["dst"]
try:
sql = "UPDATE `sb_parameters` SET `en_name`='%s' WHERE `id` = %d" % (MySQLdb.escape_string(unicode(inputData).encode('utf-8')),r[0])
print sql
curs.execute(sql)
conn.commit()
time.sleep(_sleepTime)
except EOFError:
sql = "UPDATE `sb_parameters` SET `en_name`='%s' WHERE `id` = %d" % ('',r[0])
print sql
curs.execute(sql)
conn.commit()
continue
conn.commit()
## 关闭链接
curs.close()
## 关闭数据库
conn.close()
希望本文所述对大家Python程序设计有所帮助。
标签:python,翻译
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python登录豆瓣并发帖的方法
2021-03-06 14:48:35
Python实现自动发消息自定义内容的操作代码
2023-10-17 18:01:53
![](https://img.aspxhome.com/file/2023/5/63555_0s.jpg)
简单解析PHP程序的运行流程
2023-06-22 07:35:41
![](https://img.aspxhome.com/file/2023/1/55481_0s.gif)
ASP实现防止网站被采集代码
2011-03-25 10:40:00
django框架如何集成celery进行开发
2022-09-13 11:18:24
![](https://img.aspxhome.com/file/2023/4/67784_0s.png)
一篇文章带你入门python之推导式
2022-02-05 08:29:35
为MySQL提权简单方法
2009-08-29 15:21:00
PyCharm常用配置和常用插件(小结)
2023-07-21 03:21:17
![](https://img.aspxhome.com/file/2023/7/63617_0s.png)
ASP.NET MVC Bundles 用法和说明(打包javascript和css)
2023-07-17 01:20:59
特殊字符、常规符号及其代码对照表
2010-08-24 18:13:00
![](https://img.aspxhome.com/file/UploadPic/20108/24/2010824181910416s.jpg)
python用来获得图片exif信息的库实例分析
2022-07-16 12:29:38
动易CMS:九个常见的错误原因分析及解决方法(ZT)
2008-07-01 12:40:00
Django模板获取field的verbose_name实例
2023-07-30 06:53:55
python pycharm的安装及其使用
2023-11-04 20:27:06
![](https://img.aspxhome.com/file/2023/8/80498_0s.jpg)
用FrontPage制作缩略图和图片重叠效果
2007-11-18 14:45:00
TXT.WORD文档下载另存为,而不是在浏览器中打开
2007-10-25 11:43:00
XML简易教程之三
2008-09-05 17:19:00
在opera里css出现渲染问题
2009-01-15 12:19:00
javascript面向对象编程(一)
2008-03-07 12:54:00
八个有用的WordPress的SQL语句
2009-01-12 18:54:00