python automatic translation implementation

高洛峰
Release: 2017-03-02 16:02:59
Original
2064 people have browsed it

The example in this article describes the implementation method of python automatic translation. I share it with you for your reference, the details are as follows:

I have learned the basics of python before, but generally have not used it. Later, there was a parameter table that required Chinese and English. After thinking about it, I decided to use python. The Baidu translation interface called has experienced problems such as garbled characters and incomplete modules. Generally google, do it at the same time. share.

#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()
Copy after login


For more articles related to python automatic translation implementation, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template