zoukankan      html  css  js  c++  java
  • python really battery includeded

    see the http://code.activestate.com/recipes/576890-python-wrapper-for-google-ajax-language-api/

    really cool isn't it?

    A Python Wrapper for Google AJAX Language API, Uses Google Language Detection, in cases source language is not provided with the source text, Splits up text if it's longer then 4500 characters, as a limit put up by the API. Working fine for me, please let me know if i missed something.

    Python, 53 lines
    Copy to clipboard

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    # -*- coding: utf-8 -*-
    
    import re
    import sys
    import urllib
    import simplejson
    
    baseUrl = "http://ajax.googleapis.com/ajax/services/language/translate"
    
    def getSplits(text,splitLength=4500):
        '''
        Translate Api has a limit on length of text(4500 characters) that can be translated at once, 
        '''
        return (text[index:index+splitLength] for index in xrange(0,len(text),splitLength))
    
    
    def translate(text,src='', to='en'):
        '''
        A Python Wrapper for Google AJAX Language API:
        * Uses Google Language Detection, in cases source language is not provided with the source text
        * Splits up text if it's longer then 4500 characters, as a limit put up by the API
        '''
    
        params = ({'langpair': '%s|%s' % (src, to),
                 'v': '1.0'
                 })
        retText=''
        for text in getSplits(text):
                params['q'] = text
                resp = simplejson.load(urllib.urlopen('%s' % (baseUrl), data = urllib.urlencode(params)))
                try:
                        retText += resp['responseData']['translatedText']
                except:
                        raise
        return retText
    
    
    def test():
        msg = "      Write something You want to be translated to English,\n"\
            "      Enter ctrl+c to exit"
        print msg
        while True:
            text = raw_input('#>  ')
            retText = translate(text)
            print retText
            
    
    if __name__=='__main__':
        try:
            test()
        except KeyboardInterrupt:
            print "\n"
            sys.exit(0)
    
  • 相关阅读:
    CDN是如何工作的?
    JQuery UI的拖拽功能
    .net/C#开源操作系统学习系列
    [开源]KJFramework.Message 智能二进制消息框架 新能力
    [ASP.NET MVC]通过对HtmlHelper扩展简化“列表控件”的绑定
    Sencha Touch 2 官方文档翻译之 Managing Dependencies with MVC(管理MVC依赖项)
    Node.JS环境搭建手顺(无脑操作)
    找到拥有相同标签的用户对
    《算法导论》
    Controller的激活
  • 原文地址:https://www.cnblogs.com/lexus/p/1853764.html
Copyright © 2011-2022 走看看