python自動(dòng)翻譯實(shí)現(xiàn)方法
本文實(shí)例講述了python自動(dòng)翻譯實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
以前學(xué)過python的基礎(chǔ),一般也沒用過。后來有一個(gè)參數(shù)表需要中英文。想了一下,還是用python做吧。調(diào)用的百度翻譯接口,經(jīng)歷了亂碼、模塊不全等問題。一般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() ## 關(guān)閉鏈接 curs.close() ## 關(guān)閉數(shù)據(jù)庫 conn.close()
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python使用SQLite和Excel操作進(jìn)行數(shù)據(jù)分析
這篇文章主要介紹了Python使用SQLite和Excel操作進(jìn)行數(shù)據(jù)分析,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01PyQt5入門之基于QListWidget版本實(shí)現(xiàn)圖片縮略圖列表功能
這篇文章主要介紹了PyQt5入門之基于QListWidget版本實(shí)現(xiàn)圖片縮略圖列表功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09