python自动翻译实现

本文实例讲述了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自动翻译实现相关文章请关注php中文网!

Posted in 未分类

发表评论