【问题标题】:Nhunspell cannot add new word to dictionaryNhunspell 无法在字典中添加新单词
【发布时间】:2014-08-03 16:53:21
【问题描述】:

我想使用 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),还是只是将其添加到内存中而不对字典文件执行任何操作?

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

【问题讨论】:

  • 我在 hunspell c++ 中做了一些调查,但它看起来并没有保存文件的功能。我可能是错的。 C++ Manager Headers 似乎没有任何存档
  • 嗨@Prescott,我用C#而不是C++工作
  • NHunspell 是 C++ 原生 dll 的包装器。在研究 .Add() 方法以确定它是否修改了文件本身(与仅在内存字典中的内部文件相比)时,我不得不深入研究 C++,因为 C# 包装器会调用它。
  • 哦,所以答案是 NHunspell 不会将任何内容保存回字典?
  • 您在 Web 服务器上使用 Hunspell。强烈建议在多线程环境中使用 SpellFactory 类 (help.crawler-lib.net/NHunspell/html/…)。 (codeproject.com/Articles/43769/…)

标签: c# dictionary nhunspell


【解决方案1】:

最后,随着 Prescott 的评论,我在CodeProject 找到了作者 (Thomas Maierhofer) 的这条信息:

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

【讨论】:

  • 请记住,Hunspell 对象不是线程安全的。如果使用单例模式,则必须确保对象不会被两个线程同时使用。
猜你喜欢
  • 1970-01-01
  • 2018-06-07
  • 2014-04-02
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 2023-03-20
  • 2013-02-21
相关资源
最近更新 更多