简体   繁体   中英

Nhunspell cannot add new word to dictionary

I want to add some custom words to dictionay by using Hunspell:

I load from dictionary in the constructor:

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"));
}

This function adds a new word to the dictionary:

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

After I add a word to the dictionary, if I spell this word in the same request:

_hunspell.Spell(word)

It returns true , but if I spell this word in another request, it returns false

I check both files .aff and .dic , I see it does not change after _hunspell.Add(word); , so when another request is sent, the constructor creates a new Hunspell instance from the original dictionary.

My question is: Does the Nhunspell add the new word to the dictionary and save it back to the physical file (*.aff or *.dic), or does it just add it to memory and do nothing with the dictionary file?

Did I do something wrong to add a new word to the dictionary?

Finally, with Prescott comment, I found this information from the author (Thomas Maierhofer) in CodeProject :

You can use Add() and AddWithAffix() to add your words into a already created Hunspell object. The Dictionary files are not modified, so this addition must be done every time you create a Hunspell object. You can store your own dictionary whereever you want and add the words from your dictionary after you create a Hunspell object. After that you can spell check with your own words in the dictionary.

It's mean nothing save back to dictionary file, so I change my Nhunspell class to singleton to keep the Hunspell object.

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);
    }
}

I can spell word every where with this line:

 var isCorrect = NhunspellHelper.Instance.Spell("word");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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