22additional dictionaries if provided.
33"""
44
5- import pathlib
65import logging
76import importlib .resources
87import spellchecker
@@ -22,46 +21,35 @@ def create_checker(dict_list: list[str] = None) -> spellchecker.SpellChecker:
2221 # load the English dictionary
2322 lib_path = importlib .resources .files (spellchecker )
2423 english_dict = str (lib_path ) + "/resources/en.json.gz"
25- logger .info ("Loading English dictionary from: %s" , english_dict )
2624 checker .word_frequency .load_dictionary (english_dict )
27- logger .info ("# of words: %d" , checker .word_frequency .unique_words )
25+ logger .info ("Loaded %s" , english_dict )
26+ logger .info ("%d words" , checker .word_frequency .unique_words )
2827
2928 # load the additional dictionaries
30- if not isinstance (dict_list , list ):
29+ if not isinstance (dict_list , list ) or not dict_list :
3130 return checker
32- if len (dict_list ) > 0 :
33- for d in dict_list :
34- if isinstance (d , pathlib .PosixPath ):
35- # local file path
36- try :
37- checker .word_frequency .load_text_file (d )
38- logger .info ("Loading dictionary: %s" , d )
39- except IsADirectoryError :
40- # if a directory is provided, load all text files in it
41- for file in d .glob ("*.txt" ):
42- try :
43- checker .word_frequency .load_text_file (file )
44- logger .info ("Loading dictionary: %s" , file )
45- except FileNotFoundError :
46- logger .error ("File not found: %s" , file )
47- continue
48- else :
49- # load dictionary from URL
50- try :
51- response = requests .get (d )
52- response .raise_for_status ()
53- checker .word_frequency .load_text (response .text )
54- logger .info ("Loading dictionary URL: %s" , d )
55- except requests .exceptions .MissingSchema :
56- # URL didn't work so assume it's a local file path
57- try :
58- checker .word_frequency .load_text_file (d )
59- logger .info ("Loading dictionary: %s" , d )
60- except FileNotFoundError :
61- logger .error ("File not found: %s" , d )
62- continue
63- except requests .exceptions .RequestException as e :
64- logger .error ("Error loading dictionary from URL %s: %s" , d , e )
65- logger .info ("# of words: %d" , checker .word_frequency .unique_words )
31+
32+ for d in dict_list :
33+ dstring = str (d )
34+
35+ # load dictionary from URL
36+ try :
37+ response = requests .get (dstring )
38+ response .raise_for_status ()
39+ checker .word_frequency .load_text (response .text )
40+
41+ except requests .exceptions .MissingSchema :
42+ # URL didn't work so assume it's a local file path
43+ try :
44+ checker .word_frequency .load_text_file (dstring )
45+ except IOError :
46+ logger .error ("Error loading %s" , dstring )
47+ continue
48+
49+ except requests .exceptions .RequestException as e :
50+ logger .error ("Error loading dictionary from URL %s: %s" , dstring , e )
51+
52+ logger .info ("Loaded %s" , dstring )
53+ logger .info ("%d words" , checker .word_frequency .unique_words )
6654
6755 return checker
0 commit comments