我可以检测unicode字符串语言代码吗?

问题描述 投票:0回答:7

我面临着一种情况,我正在阅读一串文本,并且需要检测语言代码(en、de、fr、es 等)。

有没有一种简单的方法可以在Python中做到这一点?

python unicode internationalization detection
7个回答
13
投票

如果您需要检测响应用户操作的语言,那么您可以使用 google ajax language API:

#!/usr/bin/env python
import json
import urllib, urllib2

def detect_language(text,
    userip=None,
    referrer="http://stackoverflow.com/q/4545977/4279",
    api_key=None):        

    query = {'q': text.encode('utf-8') if isinstance(text, unicode) else text}
    if userip: query.update(userip=userip)
    if api_key: query.update(key=api_key)

    url = 'https://ajax.googleapis.com/ajax/services/language/detect?v=1.0&%s'%(
        urllib.urlencode(query))

    request = urllib2.Request(url, None, headers=dict(Referer=referrer))
    d = json.load(urllib2.urlopen(request))

    if d['responseStatus'] != 200 or u'error' in d['responseData']:
        raise IOError(d)

    return d['responseData']['language']

print detect_language("Python - can I detect unicode string language code?")

输出

en

谷歌翻译API v2

默认限制 100000 个字符/天(一次不超过 5000 个)。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib, urllib2

from operator import itemgetter

def detect_language_v2(chunks, api_key):
    """
    chunks: either string or sequence of strings

    Return list of corresponding language codes
    """
    if isinstance(chunks, basestring):
        chunks = [chunks] 

    url = 'https://www.googleapis.com/language/translate/v2'

    data = urllib.urlencode(dict(
        q=[t.encode('utf-8') if isinstance(t, unicode) else t 
           for t in chunks],
        key=api_key,
        target="en"), doseq=1)

    # the request length MUST be < 5000
    if len(data) > 5000:
        raise ValueError("request is too long, see "
            "http://code.google.com/apis/language/translate/terms.html")

    #NOTE: use POST to allow more than 2K characters
    request = urllib2.Request(url, data,
        headers={'X-HTTP-Method-Override': 'GET'})
    d = json.load(urllib2.urlopen(request))
    if u'error' in d:
        raise IOError(d)
    return map(itemgetter('detectedSourceLanguage'), d['data']['translations'])

现在您可以请求显式检测语言

def detect_language_v2(chunks, api_key):
    """
    chunks: either string or sequence of strings

    Return list of corresponding language codes
    """
    if isinstance(chunks, basestring):
        chunks = [chunks] 

    url = 'https://www.googleapis.com/language/translate/v2/detect'

    data = urllib.urlencode(dict(
        q=[t.encode('utf-8') if isinstance(t, unicode) else t
           for t in chunks],
        key=api_key), doseq=True)

    # the request length MUST be < 5000
    if len(data) > 5000:
        raise ValueError("request is too long, see "
            "http://code.google.com/apis/language/translate/terms.html")

    #NOTE: use POST to allow more than 2K characters
    request = urllib2.Request(url, data,
        headers={'X-HTTP-Method-Override': 'GET'})
    d = json.load(urllib2.urlopen(request))

    return [sorted(L, key=itemgetter('confidence'))[-1]['language']
            for L in d['data']['detections']]

示例:

print detect_language_v2(
    ["Python - can I detect unicode string language code?",
     u"матрёшка",
     u"打水"], api_key=open('api_key.txt').read().strip())

输出

[u'en', u'ru', u'zh-CN']

7
投票

在我的例子中,我只需要确定两种语言,所以我只检查第一个字符:

import unicodedata

def is_greek(term):
    return 'GREEK' in unicodedata.name(term.strip()[0])


def is_hebrew(term):
    return 'HEBREW' in unicodedata.name(term.strip()[0])

6
投票

看看猜测语言

尝试确定所选 Unicode (utf-8) 文本的自然语言。

但正如其名称所示,它会猜测语言。您不能期望 100% 正确的结果。

编辑:

猜测语言未维护。但是有一个fork(支持python3):guess_language-spirit


5
投票

查看自然语言工具包使用 Python 进行自动语言识别以获取想法。

我想知道贝叶斯过滤器是否可以正确表达语言,但我现在无法编写概念证明。


3
投票

这里有一篇有用的文章建议这个名为 CLD 的开源是检测 Python 语言的最佳选择。

文章展示了 3 种解决方案之间的速度和准确性比较:

  1. 语言检测或其Python端口langdetect
  2. 蒂卡
  3. Chromium 语言检测 (CLD)

我在

langdetect
上浪费了时间,现在我正在切换到
CLD
,它比
langdetect
快 16 倍,并且准确率高达 98.8%


1
投票

尝试

Universal Encoding Detector
它是
chardet
模块从 Firefox 到 Python 的端口。


-1
投票

如果您只有有限数量的可能语言,您可以使用每种语言的一组词典(可能只包括最常见的单词),然后根据词典检查输入中的单词。

© www.soinside.com 2019 - 2024. All rights reserved.