python - chardet.detect 返回空语言
问题描述
我正在使用 chardet.detect 来检测字符串的语言,就像这里建议的解决方案之一一样
我的代码如下所示:
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 作为我的解决方案,因为我已经在我的应用程序中导入了它,并且我希望它尽可能的纤细
解决方案
chardet 模块不太擅长检测字符集或语言。基于Python 中列出的选项:如何确定语言?我发现 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
模块可以正确处理所有这些问题,因此这也可能是一个不错的选择。
推荐阅读
- javascript - 是否可以使用 python 编写网站的后端,以便我可以调用 python 方法并显示其输出?
- python - 如何使用 N-Beats 算法和 pytorch 预测来预测 K 单变量时间序列?
- javascript - 有人可以解释一下这段代码的含义吗?
- c# - Xamarin Forms TapGestureRecognizer 未发出命令
- python - 如何从 Python 执行 Common Lisp 代码
- java - Android Studio 无法解析任何 Java 对象,但会构建和部署运行的 APK
- python-3.x - Python类构造函数中的空列表导致错误
- r - 在 R 的数据框中过滤“仅”
- apache-spark - 获取 TypeError:在 Apache Spark / Databricks 中尝试流数据时,路径只能是单个字符串
- c - 消除字符串中所有多余的空格