gpt4 book ai didi

python - 如何使用 pyhunspell 向 .dic/.aff 文件添加新词?

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:52 24 4
gpt4 key购买 nike

我正在使用 pyhunspell,它是 HunSpell 的 python 包装器,它是一个基于 .dic/.aff 文件的拼写检查器、词干分析器、单词分析器。pyhunspell 的文档是 found here .不幸的是,文档页面没有演示如何向字典中添加新词/通过 Python 脚本扩展字典。然而 source code pyhunspell 包含一个 add() 函数,但与其他函数不同的是,没有对 add() 的解释,例如这个函数需要什么参数。以前有没有人设法调用过这个函数,并且可以给我写一个如何使用这个 add() 函数的例子?

这是我想调用的函数的 C 源代码,但我的 C 语言太有限,无法理解这里发生了什么。

static PyObject *
HunSpell_add(HunSpell * self, PyObject *args)
{
char *word;
int retvalue;

if (!PyArg_ParseTuple(args, "s", &word))
return NULL;
retvalue = Hunspell_add(self->handle, word);

return Py_BuildValue("i", retvalue);
}

static PyObject *
HunSpell_add_with_affix(HunSpell * self, PyObject *args)
{
char *word, *example;
int retvalue;

if (!PyArg_ParseTuple(args, "ss", &word, &example))
return NULL;
retvalue = Hunspell_add_with_affix(self->handle, word, example);

return Py_BuildValue("i", retvalue);
}

谢谢。


更新:

正如@RedX 所暗示的那样,我尝试使用 1 或 2 个参数调用 add() 函数。以下是我的发现:

例如,我使用 hu_HU(匈牙利语)词典文件(.dic 和 .aff),这是我需要为应用程序扩展专业领域词汇的文件。为了使示例对说英语的人透明,我选择了一个尚未包含在 hu_HU 词典中的名称 (McNamara)。由于匈牙利语是一种词法非常丰富的语言,所以我需要关心词的偏角,否则词干提取将不起作用。

McNamara 遵循与 Tamara 相同的偏角模式,它已经被识别并且可以被正确地提取,例如对于 Tamarával 这个词(“与 Tamara”)

import hunspell

hobj = hunspell.HunSpell('/usr/share/hunspell/hu_HU.dic', '/usr/share/hunspell/hu_HU.aff')
stem = hobj.stem("Tamarával")
print(stem)

将输出 ['Tamara'],这是正确的。

现在,如果我尝试用新词和示例调用 add():

import hunspell

hobj = hunspell.HunSpell('/usr/share/hunspell/hu_HU.dic', '/usr/share/hunspell/hu_HU.aff')
hobj.add("McNamara", "Tamara")

这会抛出一个 TypeError: function takes exactly 1 argument (2 given)。然而@RedX 基于 C 代码的建议似乎合乎逻辑。

此外,如果我用一个参数调用 add("McNamara"),它似乎只会为当前 session 添加新词,而不是为脚本的下一次运行添加新词,例如:

hobj.add("McNamara")
print(hobj.spell("McNamara"))

这会打印出 True,但下次我仅使用最后一行运行脚本时,它将返回 False

最佳答案

您错过了 C 绑定(bind)代码中的一个细节。有两种不同的功能。

  • 第一个是add,它将一个单词添加到当前使用的字典中(仅用于运行时)。它允许您对其调用 spell
  • 第二个是add_with_affix,它允许您在字典中添加一个词并从另一个词中复制标志。

例如(处理法语口述):

>>> hf.spell("pipoteuse")
False # word not in the dict
>>> hf.stem("pipoteuses") # try some classic plural stem
[] # no stem
>>> hf.analyze("pipoteuse")
[] # no analysis
>>> hf.add_with_affix("pipoteuse", "chanteuse")
0 # 0 = succesful operation
>>> hf.spell("pipoteuse")
True # word in the dict now
>>> hf.analyze('pipoteuse')
[b' st:pipoteuse is:fem is:sg'] # flags copied from "chanteuse", is feminin singular and stem is itself (like chanteuse)
>>> hf.stem("pipoteuses")
[b'pipoteuse'] # now stem the plural of this fake word

正在更新一些链接:

关于python - 如何使用 pyhunspell 向 .dic/.aff 文件添加新词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31914522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com