Python 库识别文本中的语种, 语种检测

本文介绍三个本地运行,不需要联网就能识别文本中的语种的python库。

1. Chardet

Chardet 库是 python 中的字符编码自动检测。encode 即编码
安装:pip install chardet

本地字符串语种检测使用:

import chardet

print(chardet.detect("Я люблю вкусные пампушки".encode('cp1251')))


输出:
{'encoding': 'windows-1251', 'confidence': 0.9787849417942193, 'language': 'Russian'}

检测文件xml中的语种:

import glob
from chardet.universaldetector import UniversalDetector

detector = UniversalDetector()
for filename in glob.glob('*.xml'):
    print(filename.ljust(60), end='')
    detector.reset()
    for line in open(filename, 'rb'):
        detector.feed(line)
        if detector.done: break
    detector.close()
    print(detector.result)

2. Langdetect

非常实用的小需求python库。
安装:pip install langdetect

检测:

from langdetect import detect, DetectorFactory, detect_langs
# DetectorFactory.seed = 0
print(detect('今一はお前さん'))


输出:
ja

语言检测算法是不确定的,这意味着如果您尝试在太短或太模糊的文本上运行它,则每次运行它时可能会得到不同的结果。如果要强制执行一致的结果,可以在语言检测之前调用DetectorFactory.seed = 0

如果想要输出排名靠前的语言的概率:

from  langdetect  import  detect_langs 
detect_langs ( "Otec matka syn." ) 


输出:
[ sk : 0.572770823327 ,  pl : 0.292872522702 ,  cs : 0.134356653968 ]

3. Langid

安装:pip install langid

检测:

import langid
print(langid.classify("今一はお前さん"))


输出:
('ja', -143.23792815208435)

以上。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值