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相关内容感兴趣的读者可查看本站专题:《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登...
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登...
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接...
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密...
抽丝剥茧成功破解红人点集的签名加密算法 抽丝剥茧破解登录签...
轻松绕过 Graphql 接口爬取有米有数的商品数据 有米有数数据...