Googletranslate Python gadgets

Source: Internet
Author: User

I think Google online translation is quite useful. If I want to write a small tool, I can use it locally. I found two tools on the Internet that are not very useful (using python to call Google translation; using Google translation for Python ),

Now I have pasted my own code and used a regular expression to extract the translation content:

View code

 1 # -*- coding:utf-8 -*-
2  import urllib, urllib2
3  import re
4 import locale
5
6 def getTranslateHtml(text):
7 values = {'hl':'zh-CN', 'ie':'utf8', 'text':text, 'langpair':"en|zh-CN"}
8 url = 'http://translate.google.cn/translate_t'
9 data = urllib.urlencode(values)
10 req = urllib2.Request(url, data)
11 req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
12 reponse = urllib2.urlopen(req)
13 return reponse.read()
14
15 def getTranslateText(html):
16 rettxt = ''
17 m = re.search('<span id=result_box.*?><span .*?>.*?</span></span>', html)
18 if m is not None:
19 rettxt = re.sub('</?span.*?>', '', m.group(0))
20 return rettxt.decode('utf8').encode(locale.getpreferredencoding())
21
22 if __name__ == '__main__':
23
24 while True:
25 text = raw_input('Enter translate text(q exit):')
26 if text == 'q':
27 break
28
29 print getTranslateText(getTranslateHtml(text))

The program running effect is as follows:

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.