"Python" Python's Urllib, Urllib2 module calls "Baidu Translator" API for batch automatic translation

Source: Internet
Author: User

1. Description of the problem

In the text processing, often back to the text of the various languages of the mixed situation, including: English, Japanese, Russian, French, and so on, need to be in different languages of the language batch translated into Chinese for processing. The translation API provided by Baidu can be directly called by Python for batch translation.

Baidu Translation API detailed documents see: Baidu translation API document


2. Problem solving

Development environment: Linux

Separate Chinese and non-Chinese from the text and translate non-Chinese parts.

The Python code is as follows: translate.py

#!/usr/bin/python#-*-coding:utf-8-*-import sysreload (SYS) sys.setdefaultencoding ("UTF8") import json                                                                   #导入json模块import Urllib #导入urllib模块from urllib2 Import Request, Urlopen, Urlerror, Httperror #导入urllib2模块def t  Ranslate (Inputfile, outputFile): fin = open (inputfile, ' r ') #以读的方式打开输入文件fout =                                                    Open (OutputFile, ' W ') #以写的方式代开输出文件for Eachline in fin:  #按行读入文件line = Eachline.strip () #去除每行首尾可能的空格等quoteStr = Urllib.quote (line) #将读入的每行内容转换成特定的格式进行翻译url = ' http://openapi.baidu.com/public/2.0/bmt/ Translate?client_id=wtzffyttxytocv7wjurfgr9w&q= ' + quotestr + ' &from=auto&to=zh ' try:resultPage = Urlopen                         (URL)      #调用百度翻译API进行批量翻译except Httperror as E:print (' the server couldn\ ' t fulfill the request ') Print (' Error code: ', E.code) except Urlerror as E:print (' We failed to reach a server. ') Print (' Reason: ', E.reason) except Exception, E:print ' translate error. ' Print Econtinueresultjason = Resultpage.read (). Decode (' Utf-8 ') #取得翻译的结果, the result of the translation is the JSON format js = Nonetry:js = Json.loads (Resultjason) #将 The JSON format results are translated into Python's dictionary structure except Exception, E:print ' loads JSON error. ' Print Econtinuekey = U ' trans_result ' if key in JS:DST                                          = js["Trans_result"][0]["DST"] #取得翻译后的文本结果outStr = DSTELSE:OUTSTR = line  #如果翻译出错, output the original text Fout.write (Outstr.strip (). Encode (' utf-8 ') + ' \ n ') #将结果输出fin. Close () Fout.close () if __name__ = = ' __main__ ': Translate (sys.argv[1], sys.argv[2]) #通过获得命令行参数获得输入输出文件名来执行, convenient

After the program is complete, enter it on the Linux command line: Python translate.py myinput.txt myoutput.txt

will be able to execute. The final translation results are written to the output file Myoutput.txt.


3. Note

(1) The first few lines of the program are written in general, in order to solve the problem of Chinese coding that may occur frequently.

(2) In line 18th, the text that needs to be translated needs to be translated into a specific format code through the quote function.

(3) The 19th line, the URL of "&from=auto&to=zh", from the back of the source language code, to follow the code of the destination language, such as: En for Chinese, en for English, auto for any language automatically.



I hope we have some help, thank you.

Python python's urllib, Urllib2 module calls "Baidu Translator" API for batch automatic translation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.