我使用chardet.detect是为了检测字符串的语言,就像建议的here解决方案之一一样
我的代码如下所示:
import chardet
print(chardet.detect('test'.encode()))
print(chardet.detect('בדיקה'.encode()))
print(chardet.detect('тест'.encode()))
print(chardet.detect('テスト'.encode()))我得到的结果如下:
{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
{'encoding': 'utf-8', 'confidence': 0.9690625, 'language': ''}
{'encoding': 'utf-8', 'confidence': 0.938125, 'language': ''}
{'encoding': 'utf-8', 'confidence': 0.87625, 'language': ''}我的预期结果应该如下所示:
{'encoding': 'ascii', 'confidence': 1.0, 'language': 'English'}
{'encoding': 'utf-8', 'confidence': 0.9690625, 'language': 'Hebrew'}
{'encoding': 'utf-8', 'confidence': 0.938125, 'language': 'Russian'}
{'encoding': 'utf-8', 'confidence': 0.87625, 'language': 'Japanese'}我更喜欢使用chardet作为我的解决方案,因为我已经在我的应用程序中导入了它,并且我想让它尽可能地精简
发布于 2020-05-06 01:01:02
chardet模块在检测字符集和语言方面都不是很好。根据Python: How to determine the language?上列出的选项,我发现pyCLD3很容易安装,即使只有相当短的文本片段也能提供很好的检测,尽管对于像你的测试这样的单个单词来说并不完美:
>>> cld3.get_language("test")
LanguagePrediction(language='ko', probability=0.3396911025047302, is_reliable=False, proportion=1.0)
>>> cld3.get_language("בדיקה")
LanguagePrediction(language='iw', probability=0.9995728731155396, is_reliable=True, proportion=1.0)
>>> cld3.get_language("тест")
LanguagePrediction(language='bg', probability=0.9895398616790771, is_reliable=True, proportion=1.0)
>>> cld3.get_language("テスト")
LanguagePrediction(language='ja', probability=1.0, is_reliable=True, proportion=1.0)看起来四分之三因为тест也是保加利亚人。langid模块可以正确地处理所有这些问题,因此这也可能是一个不错的选择。
https://stackoverflow.com/questions/61596125
复制相似问题