python - 如何将 Polyglot Detector 功能应用于数据框

标签 python pandas polyglot

假设我有一个名为 df.Text 的列,其中包含文本(超过 1 个句子)并且我想使用多语言 Detector 来检测语言并存储值在新列 df['Text-Lang'] 中,我如何确保我还捕获了其他详细信息,例如 codeconfidence

testEng ="This is English"
lang = Detector(testEng)
print(lang.language)

返回

name: English code: en confidence: 94.0 read bytes: 1920

但是

df['Text-Lang','Text-LangConfidence']= df.Text.apply(Detector)

结束于

AttributeError: 'float' object has no attribute 'encode' and Detector is not able to detect the language reliably.

我是否错误地应用了 Detector 函数或错误地存储了输出或其他原因?

最佳答案

首先,如果你只需要polyglot来进行语言检测,你最好直接使用pycld2,那是在幕后使用的。它具有很多更简洁的 API。

也就是说,您陈述的错误来自您的 Text 列中的一个值,它是一个实数。因此,您必须将这样的值转换为字符串。

您会遇到的下一个问题是最小文本长度。如果文本太短,polyglot 将抛出异常。您必须通过传递 quiet=True 来消除异常。

现在,应用 Detector 将返回一个对象。所以你必须解析它来提取你想要的信息。要提取语言名称,您必须导入 icu 模块(它是 polyglot 的依赖项,因此您已经安装了它):

import icu
df.Text = df.Text.astype(str)
df['poly_obj'] = df.Text.apply(lambda x: Detector(x, quiet=True))
df['Text-lang'] = df['poly_obj'].apply(lambda x: icu.Locale.getDisplayName(x.language.locale))
df['Text-LangConfidence'] = df['poly_obj'].apply( lambda x: x.language.confidence)

之后,您可以删除 poly_obj 列。

关于python - 如何将 Polyglot Detector 功能应用于数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51503199/

相关文章:

python - 有没有办法从内存而不是磁盘导入 Python egg?

python - 根据百分比从列表中提取元素

python - 什么是特征哈希(hashing-trick)?

python - python3中的日期时间到十进制小时和分钟

java - 异常: "Invalid action number found in internal parse table." Polyglot Exception

python - 在 python 中确定文本语言和纠正拼写错误的最佳算法是什么?

python - django模型方法中的get_full_path

python - 设置蛾缩写的语言

python - 按 Pandas 数据框和条件分组

java - 用于多语言编程的 IDE