From c00863f4c916be4b2adecb138e5a64d6813226f3 Mon Sep 17 00:00:00 2001 From: Guillaume Ayoub Date: Sun, 15 Dec 2024 20:10:27 +0100 Subject: [PATCH] Allow dicts to be open from filenames and Paths Fix #68. --- pyphen/__init__.py | 14 ++++++-------- tests/test_pyphen.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/pyphen/__init__.py b/pyphen/__init__.py index 19c058f..895009b 100755 --- a/pyphen/__init__.py +++ b/pyphen/__init__.py @@ -208,20 +208,18 @@ class Pyphen: def __init__(self, filename=None, lang=None, left=2, right=2, cache=True): """Create an hyphenation instance for given lang or filename. - :param filename: filename of hyph_*.dic to read + :param filename: filename or Path of hyph_*.dic to read :param lang: lang of the included dict to use if no filename is given :param left: minimum number of characters of the first syllabe :param right: minimum number of characters of the last syllabe :param cache: if ``True``, use cached copy of the hyphenation patterns """ - if not filename: - filename = LANGUAGES[language_fallback(lang)] - self.left = left - self.right = right - if not cache or filename not in hdcache: - hdcache[filename] = HyphDict(filename) - self.hd = hdcache[filename] + self.left, self.right = left, right + path = Path(filename) if filename else LANGUAGES[language_fallback(lang)] + if not cache or path not in hdcache: + hdcache[path] = HyphDict(path) + self.hd = hdcache[path] def positions(self, word): """Get a list of positions where the word can be hyphenated. diff --git a/tests/test_pyphen.py b/tests/test_pyphen.py index ab1db99..9ad5a01 100644 --- a/tests/test_pyphen.py +++ b/tests/test_pyphen.py @@ -8,6 +8,8 @@ """ +from pathlib import Path + import pyphen @@ -57,6 +59,20 @@ def test_personal_dict(): assert dic.inserted('autobandventieldopje') == 'au-to-band-ven-tiel-dop-je' +def test_dict_from_filename(): + """Test a dict open from filename.""" + dic_path = Path(__file__).parents[1] / 'pyphen' / 'dictionaries' / 'hyph_fr.dic' + dic = pyphen.Pyphen(filename=str(dic_path)) + assert dic.inserted('bonjour') == 'bon-jour' + + +def test_dict_from_path(): + """Test a dict open from path.""" + dic_path = Path(__file__).parents[1] / 'pyphen' / 'dictionaries' / 'hyph_fr.dic' + dic = pyphen.Pyphen(filename=dic_path) + assert dic.inserted('bonjour') == 'bon-jour' + + def test_left_right(): """Test the ``left`` and ``right`` parameters.""" dic = pyphen.Pyphen(lang='nl_NL')