本文整理汇总了Python中enchant.checker.SpellChecker.suggest方法的典型用法代码示例。如果您正苦于以下问题:Python SpellChecker.suggest方法的具体用法?Python SpellChecker.suggest怎么用?Python SpellChecker.suggest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类enchant.checker.SpellChecker
的用法示例。
在下文中一共展示了SpellChecker.suggest方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: suggest_correction
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
def suggest_correction(file_path):
"""return string representing the spell-corrected content of
the file specified by the file_path
"""
with open(file_path, "r") as file_to_check:
data = file_to_check.read()
checker = SpellChecker("en_US")
checker.set_text(data)
for err in checker:
# avoid IndexOutOfBounds
err.replace(checker.suggest()[0])
return checker.get_text()
示例2: doSpelling
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
def doSpelling(str):
chkr = SpellChecker("en_GB"); # any english dictionary
chkr.set_text(str);
## we can do more similarity ratio checks as well :P right now pick the best match
for err in chkr:
try:
str = re.sub(err.word,chkr.suggest(err.word)[0],str)
except Exception, e:
print 'no suggestions: {0}'.format(err.word)
continue
示例3: cleaner
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
def cleaner(tweet):
"""correct the errors in the words mispelled"""
clean_text = tweet
#better performance in time elaboration in opposition with the spellchecker of the textblob (0.32s vs 0.85s)
from enchant.checker import SpellChecker
chkr = SpellChecker("en_GB") #you can set "en_US" to use the us dictionary
chkr.set_text(clean_text)
#print clean_text
for err in chkr:
if (len(err.word)>3 and re.search(u'\u2019',err.word)==None):
#print (err.word+" "+chkr.suggest(err.word)[0])
text = err.word
text = text.decode('latin-1')
if isinstance(text, str):
text = str(text.decode('ascii', 'ignore'))
else:
text = text.encode('ascii', 'ignore')
err.replace_always(chkr.suggest(text)[0])
clean_text = chkr.get_text()
return clean_text
示例4: spellChecker
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
class spellChecker(object):
def __init__(self, text, dictionary):
super(spellChecker, self).__init__()
log.debug("Creating the SpellChecker object. Dictionary: %s" % (dictionary,))
self.active = True
try:
if config.app["app-settings"]["language"] == "system":
log.debug("Using the system language")
self.checker = SpellChecker(filters=[twitterFilter.TwitterFilter, tokenize.EmailFilter, tokenize.URLFilter])
else:
log.debug("Using language: %s" % (languageHandler.getLanguage(),))
self.checker = SpellChecker(languageHandler.getLanguage(), filters=[twitterFilter.TwitterFilter, tokenize.EmailFilter, tokenize.URLFilter])
self.checker.set_text(text)
except DictNotFoundError:
log.exception("Dictionary for language %s not found." % (dictionary,))
wx_ui.dict_not_found_error()
self.active = False
if self.active == True:
log.debug("Creating dialog...")
self.dialog = wx_ui.spellCheckerDialog()
widgetUtils.connect_event(self.dialog.ignore, widgetUtils.BUTTON_PRESSED, self.ignore)
widgetUtils.connect_event(self.dialog.ignoreAll, widgetUtils.BUTTON_PRESSED, self.ignoreAll)
widgetUtils.connect_event(self.dialog.replace, widgetUtils.BUTTON_PRESSED, self.replace)
widgetUtils.connect_event(self.dialog.replaceAll, widgetUtils.BUTTON_PRESSED, self.replaceAll)
self.check()
self.dialog.get_response()
self.fixed_text = self.checker.get_text()
def check(self):
try:
self.checker.next()
textToSay = _(u"Misspelled word: %s") % (self.checker.word,)
context = u"... %s %s %s" % (self.checker.leading_context(10), self.checker.word, self.checker.trailing_context(10))
self.dialog.set_title(textToSay)
output.speak(textToSay)
self.dialog.set_word_and_suggestions(word=self.checker.word, context=context, suggestions=self.checker.suggest())
except StopIteration:
log.debug("Process finished.")
wx_ui.finished()
self.dialog.Destroy()
# except AttributeError:
# pass
def ignore(self, ev):
self.check()
def ignoreAll(self, ev):
self.checker.ignore_always(word=self.checker.word)
self.check()
def replace(self, ev):
self.checker.replace(self.dialog.get_selected_suggestion())
self.check()
def replaceAll(self, ev):
self.checker.replace_always(self.dialog.get_selected_suggestion())
self.check()
示例5: EnchantProxy
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
class EnchantProxy(object):
"""Wrapper alla libreria enchant"""
def __init__(self, mydict=None, lang='it_IT'):
"""[str] [,str]
Ottiene l'eventuale elenco di parole personalizzate da integrare al
dizionario ed il linguaggio da applicare - predefinito Italiano
Solleva una eccezione se `mydict` non è accessibile
"""
self._lang = lang
self._custom_dict = mydict
try:
self._chkr = SpellChecker(lang, filters=[EmailFilter, URLFilter])
self._pwl = DictWithPWL(lang, mydict) if mydict else None
except enchant.errors.DictNotFoundError as nodict_err:
raise SpellCheckError("Dizionario " + lang + " non trovato")
def check(self, text, chunk_idx):
"""(str, int) -> list of `Error`
Esegue il controllo per `testo` e ritorna una lista di oggetti
`Errore` con la parola errata e la lista dei suggerimenti.
Se la parola non viene trovata viene effettuata una ricerca anche nel
dizionario personale (`self._pwl`) se definito
`chunk_idx` è l'identificativo del testo da elaborare
"""
errors = []
self._chkr.set_text(text)
for err in self._chkr:
if self._pwl and self._pwl.check(err.word):
continue
error = Error(err.word, self._chkr.suggest(err.word), chunk_idx)
error.context = text
errors.append(error)
return errors
def upd_mydict(self, word):
"""(str)
Aggiunge la parola `word` al dizionario personalizzato (attiva per la
prossima chiamata a `check`.
**L'aggiunta viene fatta solo al dizionario personalizzato IN MEMORIA
Utilizzare `add_custom_word` per l'aggiornamento del dizionario
personalizzato su disco**
"""
if not self._pwl:
return
if self._pwl.is_added(word):
raise SpellCheckError("Parola già esistente")
self._pwl.add(word)
def add_custom_words(self, words):
"""(list of str)
Aggiunge le parole in ``words`` al dizionario personalizzato
"""
if not self._custom_dict:
raise SpellCheckError("Dizionario personalizzato non presente")
orig_words = codecs.open(self._custom_dict, encoding='utf-8').split("\n")
orig_words.extend([w for w in words if w not in orig_words])
codecs.open(
self._custom_dict, mode='w', encoding='utf-8'
).write("\n".join(orig_words))
示例6: len
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
lasterror3 = lasterror2
lasterror2 = lasterror
lasterror = err.word
Nerr += 1
repl = err.suggest()
try:
if repl[0] == err.word:
continue
err.replace(repl[0])
except:
continue
err.replace(u"spellchecker_fail")
if len(err.word) > len(repl[0]):
l = err.word[len(repl[0]):].lower()
r = chkr.suggest(err.word[len(repl[0]):])
if (len(r) > 0) and (l == r[0].lower()):
err.replace(u"wort_das_dem_spellchecker_aerger_macht")
if len(err.word) == 2 and len(repl[0]) == 2:
err.replace(u"wort_das_dem_spellchecker_aerger_macht")
text = err.get_text()
#check error ratio
Nwords = text.count(' ')
try:
er = Nerr/float(Nwords)
except:
er = 0
示例7: SpellCheck
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
class SpellCheck(wx.Panel):
def __init__(self, parent):
self.parent = parent
wx.Panel.__init__(self, parent, -1)
self.pref = Globals.pref
self.sizer = sizer = ui.VBox(padding=0, namebinding='widget').create(self).auto_layout()
h = sizer.add(ui.HBox)
h.add(ui.Label(tr("Replace with") + ':'))
h.add(ui.Text('', size=(150, -1)), name='text')
h.add(ui.Button(tr('Start')), name='btnRun').bind('click', self.OnRun)
h.add(ui.Button(tr('Replace')), name='btnReplace').bind('click', self.OnReplace)
h.add(ui.Button(tr('Replace All')), name='btnReplaceAll').bind('click', self.OnReplaceAll)
h.add(ui.Button(tr('Ignore')), name='btnIgnore').bind('click', self.OnIgnore)
h.add(ui.Button(tr('Ignore All')), name='btnIgnoreAll').bind('click', self.OnIgnoreAll)
h.add(ui.Button(tr('Add')), name='btnAdd').bind('click', self.OnAdd)
h = sizer.add(ui.HBox, proportion=1)
h.add(ui.Label(tr("Suggest") + ':'))
h.add(ui.ListBox(size=(250, -1)), name='list').binds(
(wx.EVT_LISTBOX, self._OnReplSelect),
(wx.EVT_LISTBOX_DCLICK, self.OnReplace),
)
h.add(ui.Label(tr("Available Dict") + ':'))
h.add(ui.ListBox(size=(100, -1), choices=enchant.list_languages()), name='dict_list').bind(
wx.EVT_LISTBOX, self.OnDictSelect
)
sizer.auto_fit(0)
self.init()
self._DisableButtons()
def init(self):
defLoc = locale.getdefaultlocale()[0]
if self.pref.default_spellcheck_dict:
defLoc = self.pref.default_spellcheck_dict
index = self.dict_list.FindString(defLoc)
if index > -1:
self.dict_list.SetSelection(index)
else:
defLoc = 'en_US'
self.pref.default_spellcheck_dict = defLoc
self.pref.save()
#todo add multi dict support
self.chkr = SpellChecker(defLoc)
self.mainframe = Globals.mainframe
self._buttonsEnabled = True
self.running = False
def OnRun(self, event):
if self.running:
self.running = False
self._DisableButtons()
else:
self.running = True
self.document = self.mainframe.document
if self.document.edittype != 'edit':
common.showerror(self, tr("This document can't be spell checked"))
return
self.begin_line = 0
self.begin_pos = 0
self.last_line_pos = 0
self.last_col = 0
self.ignore_list = []
self.new = True
self._Advance()
def _Advance(self):
"""Advance to the next error.
This method advances the SpellChecker to the next error, if
any. It then displays the error and some surrounding context,
and well as listing the suggested replacements.
"""
# Advance to next error, disable if not available
while 1:
try:
if self.new:
self.begin_pos = self.document.PositionFromLine(self.begin_line)
line = self.document.getLineText(self.begin_line)
line_len = self.document.GetLineEndPosition(self.begin_line) - self.begin_pos
new = False
if self.last_line_pos < line_len:
self.chkr.set_text(line[self.last_col:])
self.chkr.next()
# while self.chkr.word in self.ignore_list:
# self.chkr.next()
# pass
self.last_col += self.chkr.wordpos
self.last_line_pos = len(line[:self.last_col].encode('utf-8'))
break
except StopIteration:
if self.begin_line < self.document.GetLineCount():
self.begin_line += 1
#.........这里部分代码省略.........
示例8: spellCheckerDialog
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
class spellCheckerDialog(wx.Dialog):
def __init__(self, text, dictionary):
super(spellCheckerDialog, self).__init__(None, 1)
try:
if config.main["general"]["language"] == "system": self.checker = SpellChecker()
else: self.checker = SpellChecker(languageHandler.getLanguage())
self.checker.set_text(text)
except DictNotFoundError:
wx.MessageDialog(None, _(u"A bug has happened. There are no dictionaries available for the selected language in TW Blue"), _(u"Error"), wx.ICON_ERROR).ShowModal()
self.Destroy()
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
word = wx.StaticText(panel, -1, _(u"Mis-spelled word"))
self.word = wx.TextCtrl(panel, -1)
wordBox = wx.BoxSizer(wx.HORIZONTAL)
wordBox.Add(word)
wordBox.Add(self.word)
context = wx.StaticText(panel, -1, _(u"Context"))
self.context = wx.TextCtrl(panel, -1)
contextBox = wx.BoxSizer(wx.HORIZONTAL)
contextBox.Add(context)
contextBox.Add(self.context)
suggest = wx.StaticText(panel, -1, _(u"Suggestions"))
self.suggestions = wx.ListBox(panel, -1, choices=[], style=wx.LB_SINGLE)
suggestionsBox = wx.BoxSizer(wx.HORIZONTAL)
suggestionsBox.Add(suggest)
suggestionsBox.Add(self.suggestions)
ignore = wx.Button(panel, -1, _(u"Ignore"))
self.Bind(wx.EVT_BUTTON, self.onIgnore, ignore)
ignoreAll = wx.Button(panel, -1, _(u"Ignore all"))
self.Bind(wx.EVT_BUTTON, self.onIgnoreAll, ignoreAll)
replace = wx.Button(panel, -1, _(u"Replace"))
self.Bind(wx.EVT_BUTTON, self.onReplace, replace)
replaceAll = wx.Button(panel, -1, _(u"Replace all"))
self.Bind(wx.EVT_BUTTON, self.onReplaceAll, replaceAll)
close = wx.Button(panel, wx.ID_CANCEL)
btnBox = wx.BoxSizer(wx.HORIZONTAL)
btnBox.Add(ignore)
btnBox.Add(ignoreAll)
btnBox.Add(replace)
btnBox.Add(replaceAll)
btnBox.Add(close)
sizer.Add(wordBox)
sizer.Add(contextBox)
sizer.Add(suggestionsBox)
sizer.Add(btnBox)
panel.SetSizerAndFit(sizer)
self.check()
def check(self):
try:
self.checker.next()
textToSay = _(u"Mis-spelled word: %s") % (self.checker.word,)
context = u"... %s %s %s" % (self.checker.leading_context(10), self.checker.word, self.checker.trailing_context(10))
self.SetTitle(textToSay)
output.speak(textToSay)
self.word.SetValue(self.checker.word)
self.context.ChangeValue(context)
self.suggestions.Set(self.checker.suggest())
self.suggestions.SetFocus()
except StopIteration:
wx.MessageDialog(self, _(u"The spelling review has finished."), _("Finished"), style=wx.OK).ShowModal()
self.EndModal(wx.ID_OK)
except AttributeError:
pass
def onIgnore(self, ev):
self.check()
def onIgnoreAll(self, ev):
self.checker.ignore_always(word=self.checker.word)
self.check()
def onReplace(self, ev):
self.checker.replace(self.suggestions.GetStringSelection())
self.check()
def onReplaceAll(self, ev):
self.checker.replace_always(self.suggestions.GetStringSelection())
self.check()
示例9: static_analysis
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
def static_analysis(self, path):
"""
Perform static analysis of the notebook.
Read the notebook and check that there is no ouput and that the links
in the markdown cells are not broken.
Args:
path (string): Name of notebook.
Return:
boolean: True if static analysis succeeded, otherwise False.
"""
nb = nbformat.read(path, nbformat.current_nbformat)
#######################
# Check that the notebook does not contain output from code cells
# (should not be in the repository, but well...).
#######################
no_unexpected_output = True
# Check that the cell dictionary has an 'outputs' key and that it is
# empty, relies on Python using short circuit evaluation so that we
# don't get KeyError when retrieving the 'outputs' entry.
cells_with_output = [c.source for c in nb.cells if 'outputs' in c and c.outputs]
if cells_with_output:
no_unexpected_output = False
print('Cells with unexpected output:\n_____________________________')
for cell in cells_with_output:
print(cell+'\n---')
else:
print('no unexpected output')
#######################
# Check that all the links in the markdown cells are valid/accessible.
#######################
no_broken_links = True
cells_and_broken_links = []
for c in nb.cells:
if c.cell_type == 'markdown':
html_tree = document_fromstring(markdown.markdown(c.source))
broken_links = []
#iterlinks() returns tuples of the form (element, attribute, link, pos)
for document_link in html_tree.iterlinks():
try:
if all( prefix not in document_link[2] for prefix in ['http','https']): # Local file.
url = 'file://' + os.path.abspath(document_link[2])
else: # Remote file.
url = document_link[2]
urlopen(url)
except URLError:
broken_links.append(url)
if broken_links:
cells_and_broken_links.append((broken_links,c.source))
if cells_and_broken_links:
no_broken_links = False
print('Cells with broken links:\n________________________')
for links, cell in cells_and_broken_links:
print(cell+'\n')
print('\tBroken links:')
print('\t'+'\n\t'.join(links)+'\n---')
else:
print('no broken links')
#######################
# Spell check all markdown cells and comments in code cells using the pyenchant spell checker.
#######################
no_spelling_mistakes = True
simpleitk_notebooks_dictionary = DictWithPWL('en_US', os.path.join(os.path.dirname(os.path.abspath(__file__)),
'additional_dictionary.txt'))
spell_checker = SpellChecker(simpleitk_notebooks_dictionary, filters = [EmailFilter, URLFilter])
cells_and_spelling_mistakes = []
for c in nb.cells:
spelling_mistakes = []
if c.cell_type == 'markdown':
# Get the text as a string from the html without the markup which is replaced by space.
spell_checker.set_text(' '.join(etree.XPath('//text()')(document_fromstring(markdown.markdown(c.source)))))
elif c.cell_type == 'code':
# Get all the comments and concatenate them into a single string separated by newlines.
comment_lines = re.findall('#+.*',c.source)
spell_checker.set_text('\n'.join(comment_lines))
for error in spell_checker:
error_message = 'error: '+ '\'' + error.word +'\', ' + 'suggestions: ' + str(spell_checker.suggest())
spelling_mistakes.append(error_message)
if spelling_mistakes:
cells_and_spelling_mistakes.append((spelling_mistakes, c.source))
if cells_and_spelling_mistakes:
no_spelling_mistakes = False
print('Cells with spelling mistakes:\n________________________')
for misspelled_words, cell in cells_and_spelling_mistakes:
print(cell+'\n')
print('\tMisspelled words and suggestions:')
print('\t'+'\n\t'.join(misspelled_words)+'\n---')
else:
print('no spelling mistakes')
return(no_unexpected_output and no_broken_links and no_spelling_mistakes)
示例10: Spellcheck
# 需要导入模块: from enchant.checker import SpellChecker [as 别名]
# 或者: from enchant.checker.SpellChecker import suggest [as 别名]
class Spellcheck(object):
def __init__(self, textwidget, **kw):
lang = kw.pop('language', 'en_US')
filters = kw.pop('filters', [EmailFilter, URLFilter])
chunkers = kw.pop('chunkers', (HTMLChunker,))
self.checker = SpellChecker(lang=lang, filters=filters, chunkers=chunkers)
self.tw = textwidget
self.tw.tag_config('sp_err', background="#CCFB5D", underline=False)
def enable_spellcheck(self):
self.spellcheck_enabled = True
self._tag_remove('1.0', 'end')
ln = int(self.tw.index('end').split('.')[0])
while ln:
start = '{0}.0'.format(ln)
end = '{0}.end'.format(ln)
self._check_spelling(start, end, ln)
ln -= 1
def disable_spellcheck(self):
self.spellcheck_enabled = False
self._tag_remove('1.0', 'end')
def reload(self):
if self.spellcheck_enabled:
self.enable_spellcheck()
def run(self):
if self.spellcheck_enabled:
start, end, ln = self._findposition()
self._tag_remove(start, end)
self._check_spelling(start, end, ln)
def _findposition(self):
start = self.tw.index('insert linestart')
end = self.tw.index('insert wordstart')
ln = int(self.tw.index('insert').split('.')[0])
return (start, end, ln)
def _check_spelling(self, start, end, ln):
self.checker.set_text(self._get_text(start, end))
for e in self.checker:
begintag = '{0}.{1}'.format(ln, e.wordpos)
endtag = begintag + ('+%dchars' % len(e.word))
self._tag_word(begintag, endtag)
def _tag_word(self, begintag, endtag):
self.tw.mark_set('lt-sp_err', begintag)
self.tw.mark_set('rt-sp_err', endtag)
self.tw.mark_gravity('lt-sp_err', tk.LEFT)
self.tw.mark_gravity('rt-sp_err', tk.RIGHT)
self.tw.tag_add('sp_err', 'lt-sp_err', 'rt-sp_err')
self.tw.tag_bind('sp_err', '<Button-3>', self._get_suggestions)
def _get_text(self, start, end):
return self.tw.get(start, end)
def _get_suggestions(self, evt):
self.tw.mark_set('insert', 'current')
start = self.tw.index('insert wordstart')
end = self.tw.index('insert wordend')
suggested = self._suggest(self.tw.get(start, end))
context_menu = self._generate_contextmenu(start, end, suggested)
context_menu.tk_popup(evt.x_root, evt.y_root)
def _suggest(self, e):
return self.checker.suggest(e)
def _generate_contextmenu(self, start, end, suggested):
contextmenu = tk.Menu(self.tw, tearoff=False)
for word in suggested:
contextmenu.add_command(label=word, command=lambda start=start,
end=end, word=word: self._replace(start, end, word))
return contextmenu
def _replace(self, start, end, word):
self.tw.delete(start, end)
self.tw.insert(start, word)
self._tag_remove(start, end)
def _tag_remove(self, start, end):
self.tw.mark_unset('lt-sp_err', start)
self.tw.mark_unset('rt-sp_err', end)
self.tw.tag_remove('sp_err', start, end)