Skip to content

Commit cd0d9ce

Browse files
committed
Better exception handling
Also allow directories of dictionary text files.
1 parent e44ae2d commit cd0d9ce

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

comment_spell_check/utils/create_checker.py

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
additional dictionaries if provided.
33
"""
44

5+
import pathlib
56
import logging
67
import importlib.resources
78
import spellchecker
89
import requests
9-
import pathlib
1010

1111

1212
def create_checker(dict_list: list[str] = None) -> spellchecker.SpellChecker:
@@ -24,26 +24,44 @@ def create_checker(dict_list: list[str] = None) -> spellchecker.SpellChecker:
2424
english_dict = str(lib_path) + "/resources/en.json.gz"
2525
logger.info("Loading English dictionary from: %s", english_dict)
2626
checker.word_frequency.load_dictionary(english_dict)
27-
logger.info("number of words: %s", checker.word_frequency.unique_words)
27+
logger.info("# of words: %d", checker.word_frequency.unique_words)
2828

2929
# load the additional dictionaries
3030
if not isinstance(dict_list, list):
3131
return checker
3232
if len(dict_list) > 0:
3333
for d in dict_list:
34-
logger.info("Loading additional dictionary from: %s", d)
3534
if isinstance(d, pathlib.PosixPath):
36-
# assume it's a local file path
37-
checker.word_frequency.load_text_file(d)
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
3848
else:
3949
# load dictionary from URL
40-
if d.startswith("http://") or d.startswith("https://"):
50+
try:
4151
response = requests.get(d)
4252
response.raise_for_status()
4353
checker.word_frequency.load_text(response.text)
44-
else:
45-
# assume it's a local file path
46-
checker.word_frequency.load_text_file(d)
47-
logger.info("# of words: %s", checker.word_frequency.unique_words)
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)
4866

4967
return checker

0 commit comments

Comments
 (0)