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
2012-10-13 14:02:22 +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. """
2013-09-05 17:38:25 +12:00
2012-04-19 23:18:12 +12:00
if not enchant . dict_exists ( locale ) :
2012-10-13 14:02:22 +13:00
return " Could not find dictionary: {} " . format ( locale )
2012-04-19 23:18:12 +12:00
2013-09-05 17:38:25 +12:00
if len ( inp . split ( " " ) ) > 1 :
2013-12-01 20:44:04 +13:00
# input is a sentence
2014-02-13 15:02:44 +13:00
checker = SpellChecker ( locale )
checker . set_text ( inp )
2012-02-03 02:05:11 +13:00
2013-09-05 18:31:33 +12:00
offset = 0
2014-02-13 15:02:44 +13:00
for err in checker :
2013-09-05 17:38:25 +12:00
# find the location of the incorrect word
2013-09-05 18:31:33 +12:00
start = err . wordpos + offset
2013-09-05 17:38:25 +12:00
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 ] )
2013-09-05 17:38:25 +12:00
s_string = " \x02 {} \x02 " . format ( s_string )
2013-09-05 18:31:33 +12:00
# calculate the offset for the next word
offset = ( offset + len ( s_string ) ) - len ( err . word )
2013-09-05 17:38:25 +12:00
# 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
2013-09-05 17:38:25 +12:00
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 \x02 valid \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 \x02 invalid \x02 ! ' \
2013-09-04 23:50:57 +08:00
' (suggestions: {} ) ' . format ( inp , s_string )