如何用pyhunspell在.dic/.aff文件中添加新单词?

2024-04-29 10:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是pyhunspell,这是一个围绕HunSpell的python包装器,一个基于.dic/.aff文件的拼写检查器、词干分析器、单词分析器。 pyhunspell的文档是found here。不幸的是,doc页面没有演示如何通过Python脚本向字典中添加新词。然而,pyhunspellsource code包含一个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),这是我需要为应用程序扩展的专用领域词汇表。为了保持这个例子对讲英语的人是透明的,我选择了一个名字(McNamara),这个名字还没有出现在hu_uhu字典中。因为匈牙利语是一种形态非常丰富的语言,所以我需要注意这个词的词尾偏折,否则词干的词干就不起作用了。在

McNamara遵循与Tamara相同的倾斜模式,这种模式已经被识别,并且可以正确地词干,例如对于单词Tamaraával(“with Tamara”)

^{pr2}$

将输出['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。在


Tags: 函数selfaddreturnargswordpyobjecthunspell
1条回答
网友
1楼 · 发布于 2024-04-29 10:29:18

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

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

例如(学习法语词典):

>>> 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

一些正在进行的链接更新:

相关问题 更多 >