Nhunspell不能在字典中添加新词



我想通过使用Hunspell:

添加一些自定义单词到dictionary:

在构造函数中从字典中加载:

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),或者只是将其添加到内存中,而对字典文件不做任何操作?

我把一个新词加进字典里是不是做错了什么?

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

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

保存回字典文件没有任何意义,所以我将我的Nhunspell类更改为singleton以保留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");

最新更新