The IWordFormsProvider interface is designed to implement a word forms provider for searching by word forms. For information on searching by word forms, see the Search for different word forms page.
The IWordFormsProvider interface contains only one get_word_forms method, which returns various forms for the word passed as an argument. In Python, a provider is a plain class with the get_word_forms(word) method that returns a list of strings; a function that takes the word also works. An example implementation of a simple provider of word forms is presented below.
classSimpleWordFormsProvider:defget_word_forms(self,word):result=[]lower_word=word.lower()# We assume that the input word is in the plural, then we add the singulariflen(word)>3andlower_word.endswith("ies"):result.append(word[:-3]+"y")iflen(word)>2andlower_word.endswith("es"):result.append(word[:-2])iflen(word)>1andlower_word.endswith("s"):result.append(word[:-1])# Then we assume that the input word is in the singular, we add the pluraliflen(word)>1andlower_word.endswith("y"):result.append(word[:-1]+"ies")eliflower_word.endswith(("s","x","ch","sh")):result.append(word+"es")else:result.append(word+"s")# All rules are implemented in the EnglishWordFormsProvider classreturnresult
By default, the EnglishWordFormsProvider class is used, which for English generates various forms of nouns, adjectives, pronouns, verbs, etc. A custom provider is set with the word_forms_provider property of the Index.dictionaries object. The provider can be replaced at any time; it is not saved in the index, so it must be set each time the index is opened. An example of setting a custom provider of word forms is presented below.
fromgroupdocs.searchimportIndexfromgroupdocs.search.optionsimportSearchOptionsclassSimpleWordFormsProvider:defget_word_forms(self,word):result=[]lower_word=word.lower()# We assume that the input word is in the plural, then we add the singulariflen(word)>3andlower_word.endswith("ies"):result.append(word[:-3]+"y")iflen(word)>2andlower_word.endswith("es"):result.append(word[:-2])iflen(word)>1andlower_word.endswith("s"):result.append(word[:-1])# Then we assume that the input word is in the singular, we add the pluraliflen(word)>1andlower_word.endswith("y"):result.append(word[:-1]+"ies")eliflower_word.endswith(("s","x","ch","sh")):result.append(word+"es")else:result.append(word+"s")returnresult# Creating or opening an index in the specified folderindex=Index("./index")# Indexing documents from the specified folderindex.add("./documents")# Setting the custom word forms provider instanceindex.dictionaries.word_forms_provider=SimpleWordFormsProvider()# Creating a search options instanceoptions=SearchOptions()options.use_word_forms_search=True# Enabling search for word forms# Searching in the indexresult=index.search("relative",options)# The following words can be found:# relative# relativesfordocumentinresult:print(document.document_info.file_path)print("\tFound words:",", ".join(document.terms))