2

我想通过使用 Hunspell 在字典中添加一些自定义单词:

我从构造函数中的字典加载:

private readonly Hunspell _hunspell;
public NhunspellHelper()
{
    _hunspell = new Hunspell(
        HttpContext.Current.Server.MapPath("~/App_Data/en_US.aff"),
        HttpContext.Current.Server.MapPath("~/App_Data/en_US.dic"));
}

此函数将一个新词添加到字典中:

public void AddToDictionary(string word)
{
    _hunspell.Add(word); // or _hunspell.AddWithAffix(word, "aaa");
}

在我向字典中添加一个单词后,如果我在同一个请求中拼写这个单词:

_hunspell.Spell(word)

它返回true,但如果我在另一个请求中拼写这个词,它会返回false

我检查了两个文件.aff.dic我发现它在 之后没有改变_hunspell.Add(word);,所以当发送另一个请求时,构造函数会从原始字典中创建一个新的 Hunspell 实例。

我的问题是:Nhunspell 是否将新单词添加到字典中并将其保存回物理文件(*.aff 或 *.dic),还是只是将其添加到内存中而不对字典文件执行任何操作?

我在字典中添加新单词时做错了吗?

4

1 回答 1

1

最后,通过 Prescott 的评论,我在CodeProject中从作者 (Thomas Maierhofer) 那里找到了以下信息:

您可以使用 Add() 和 AddWithAffix() 将您的单词添加到已经创建的 Hunspell 对象中。字典文件不会被修改,因此每次创建 Hunspell 对象时都必须进行此添加。您可以在任何地方存储您自己的字典,并在创建 Hunspell 对象后添加字典中的单词。之后,您可以在字典中使用自己的单词进行拼写检查。

保存回字典文件没有任何意义,所以我将我的 Nhunspell 类更改为单例以保留 Hunspell 对象。

public class NhunspellHelper
{
    private readonly Hunspell _hunspell;
    private NhunspellHelper()
    {
        _hunspell = new Hunspell(
                        HttpContext.Current.Server.MapPath("~/App_Data/en_US.aff"),
                        HttpContext.Current.Server.MapPath("~/App_Data/en_US.dic"));
    }

    private static NhunspellHelper _instance;
    public static NhunspellHelper Instance
    {
        get { return _instance ?? (_instance = new NhunspellHelper()); }
    }

    public bool Spell(string word)
    {
        return _hunspell.Spell(word);
    }
}

我可以用这条线在每个地方拼写单词:

 var isCorrect = NhunspellHelper.Instance.Spell("word");
于 2014-06-14T01:53:33.260 回答