• 04.微博消息的语言检测


    04.微博消息的语言检测

    郑昀 201010 隶属于《02.数据解析》小节

    大意是,封装Google语言检测ajax web service的接口,输入一段话,输出语言种类。这个方法是从RssMeme.com看来的,经测试效果还不错,可用于检测微博客消息的语言,如中文、日文、韩文等。但由于Google对过于频繁的请求会重置链接,所以提请注意,这个Web Service不适合大量密集请求提交。 

    一、简单示范

    访问
    http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=hello+world
    链接,你可以看到返回结果是一个json字符串:
    {"responseData": {"language":"en","isReliable":false,"confidence":0.114892714}, "responseDetails": null, "responseStatus": 200}

    记得加版本号参数:v=1.0,否则返回如下json:
    {"responseData": null, "responseDetails": "invalid version", "responseStatus": 400}

     

    二、如果是日文微博客消息呢?

    举例,送去检测的微博客消息是:

    RT @ufotable: 本日22時より星海社ウェブサイト「最前線」にて『坂本真綾の満月朗読館』第二夜『山月記』が 配信されます。第二夜の映像演出も弊社デジタル部が担当い… http://goo.gl/brJE

    经过urlencode变换后,提交到Google,返回的结果是:

    {"responseData": {"language":"ja","isReliable":true,"confidence":0.88555187}, "responseDetails": null, "responseStatus": 200}

    这样用result['responseData']['language']就获得了语言的代号。
    只要检查这个代号不是“zh-CN”,那么就不是中文语言了。


    四、封装Google Language Detect Ajax Web Service

    示范:
    import urllib
    import httplib2
    try:
        from base import easyjson
    except:
        pass

    class Detect():
        google_api_prefix = 'http://ajax.googleapis.com/ajax/services/language/detect'
        def __init__(self, httplib2_inst=None):
            """从外可以传入httplib实例,便于在外部加设代理软件穿墙"""
            self.http = httplib2_inst or httplib2.Http()
        def post_sentence(self, q):
            return self._fetch(
                self.google_api_prefix,
                {'v':"1.0",'q':q}
                )
        def _fetch(self, url, params):
            request = url +"?"+ urllib.urlencode(params)
            resp, content = self.http.request(request, "GET")
            return easyjson.parse_json_func(content)

        def detectZHCN(self, text):
            """输入文字如果检测到是zh-CN,返回True,否则返回False"""
            data = self.post_sentence(text)['responseData']
            if(data):
                language = data['language']
                if(language=='zh-CN'):
                    return True
            return False

  • 相关阅读:
    spring注解开发AnnotationConfigApplicationContext的使用
    java.rmi.server.ExportException: Port already in use: 1099; nested exception is
    mac 入门操作
    postgreSql 常用查询总结
    Tomcat专题
    Java反射
    notepad++ jstool 插件安装
    Java集合
    Java 集合并交补
    C++回调函数(callback)的使用
  • 原文地址:https://www.cnblogs.com/zhengyun_ustc/p/1860897.html
Copyright © 2020-2023  润新知