This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/disabled_stuff/spellcheck.py

48 lines
1.5 KiB
Python
Raw Permalink Normal View History

2013-09-05 08:21:27 +02:00
from enchant.checker import SpellChecker
import enchant
2012-04-19 13:18:12 +02:00
2014-02-14 04:36:57 +01:00
from util import hook
2012-04-19 13:18:12 +02:00
locale = "en_US"
2012-02-02 14:05:11 +01:00
@hook.command
2012-02-02 14:05:11 +01:00
def spell(inp):
2013-09-04 17:50:57 +02:00
"""spell <word/sentence> -- Check spelling of a word or sentence."""
2012-04-19 13:18:12 +02:00
if not enchant.dict_exists(locale):
return "Could not find dictionary: {}".format(locale)
2012-04-19 13:18:12 +02:00
if len(inp.split(" ")) > 1:
2013-12-01 08:44:04 +01:00
# input is a sentence
checker = SpellChecker(locale)
checker.set_text(inp)
2012-02-02 14:05:11 +01:00
offset = 0
for err in checker:
# find the location of the incorrect word
start = err.wordpos + offset
finish = start + len(err.word)
# get some suggestions for it
suggestions = err.suggest()
2013-09-04 18:25:46 +02:00
s_string = '/'.join(suggestions[:3])
s_string = "\x02{}\x02".format(s_string)
# calculate the offset for the next word
offset = (offset + len(s_string)) - len(err.word)
# replace the word with the suggestions
inp = inp[:start] + s_string + inp[finish:]
return inp
2012-02-02 14:05:11 +01:00
else:
2013-12-01 08:44:04 +01:00
# input is a word
dictionary = enchant.Dict(locale)
is_correct = dictionary.check(inp)
suggestions = dictionary.suggest(inp)
2013-09-04 17:48:56 +02:00
s_string = ', '.join(suggestions[:10])
if is_correct:
return '"{}" appears to be \x02valid\x02! ' \
2013-09-04 17:50:57 +02:00
'(suggestions: {})'.format(inp, s_string)
2013-09-04 17:48:56 +02:00
else:
return '"{}" appears to be \x02invalid\x02! ' \
2013-09-04 17:50:57 +02:00
'(suggestions: {})'.format(inp, s_string)