繁体   English   中英

Nhunspell无法向词典添加新词

[英]Nhunspell cannot add new word to dictionary

我想使用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.Add(word); ,因此当发送另一个请求时,构造函数将从原始字典创建一个新的Hunspell实例。

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

为在词典中添加新单词,我做错了吗?

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

您可以使用Add()和AddWithAffix()将您的单词添加到已经创建的Hunspell对象中。 字典文件没有被修改,因此每次创建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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM