This repository has been archived on 2023-04-13. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
CloudBot/disabled_stuff/spellcheck.py

48 lines
1.5 KiB
Python
Raw Normal View History

2013-09-05 18:21:27 +12:00
from enchant.checker import SpellChecker
import enchant
2012-04-19 23:18:12 +12:00
2014-02-14 16:36:57 +13:00
from util import hook
2012-04-19 23:18:12 +12:00
locale = "en_US"
2012-02-03 02:05:11 +13:00
@hook.command
2012-02-03 02:05:11 +13:00
def spell(inp):
2013-09-04 23:50:57 +08:00
"""spell <word/sentence> -- Check spelling of a word or sentence."""
2012-04-19 23:18:12 +12:00
if not enchant.dict_exists(locale):
return "Could not find dictionary: {}".format(locale)
2012-04-19 23:18:12 +12:00
if len(inp.split(" ")) > 1:
2013-12-01 20:44:04 +13:00
# input is a sentence
checker = SpellChecker(locale)
checker.set_text(inp)
2012-02-03 02:05:11 +13: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-05 00:25:46 +08: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-03 02:05:11 +13:00
else:
2013-12-01 20:44:04 +13:00
# input is a word
dictionary = enchant.Dict(locale)
is_correct = dictionary.check(inp)
suggestions = dictionary.suggest(inp)
2013-09-04 23:48:56 +08:00
s_string = ', '.join(suggestions[:10])
if is_correct:
return '"{}" appears to be \x02valid\x02! ' \
2013-09-04 23:50:57 +08:00
'(suggestions: {})'.format(inp, s_string)
2013-09-04 23:48:56 +08:00
else:
return '"{}" appears to be \x02invalid\x02! ' \
2013-09-04 23:50:57 +08:00
'(suggestions: {})'.format(inp, s_string)