如何向.dic/中添加新词.所有带有pyhunspell的文件



我使用的是pyhunspell,这是一个围绕HunSpell的python包装器,一个。dic/。Aff文件为基础的拼写检查,词干,词分析。pyhunspell的文档可以在这里找到。不幸的是,文档页没有演示如何通过Python脚本向字典添加新词/扩展字典。然而,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("with 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"),它似乎只会为当前会话添加新词,而不是为脚本的下一次运行添加新词,例如:

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

打印True,但是下次我只运行最后一行的脚本时,它将返回False

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

  • 第一个是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

一些链接在途中更新:

  • 新的存储库在这里:https://github.com/blatinier/pyhunspell
  • 最新版本(0.4.0)现在为所有函数提供了一些pydoc。(虽然没有在线文档)

最新更新