예제 #1
0
def test_DWPWL_empty(tmp_path):
    """Test functionality of DictWithPWL using transient dicts."""
    d = DictWithPWL("en_US", None, None)
    assert d.check("hello")
    assert not d.check("helo")
    assert not d.check("Flagen")
    d.add("Flagen")
    assert d.check("Flagen")
    d.remove("hello")
    assert not d.check("hello")
    d.add("hello")
    assert d.check("hello")
예제 #2
0
def test_DWPWL(tmp_path, pwl_path):
    """Test functionality of DictWithPWL."""
    setPWLContents(pwl_path, ["Sazz", "Lozz"])
    other_path = tmp_path / "pel.txt"
    d = DictWithPWL("en_US", str(pwl_path), str(other_path))
    assert d.check("Sazz")
    assert d.check("Lozz")
    assert d.check("hello")
    assert not d.check("helo")
    assert not d.check("Flagen")
    d.add("Flagen")
    assert d.check("Flagen")
    assert "Flagen" in getPWLContents(pwl_path)
    assert "Flagen" in d.suggest("Flagn")
    assert "hello" in d.suggest("helo")
    d.remove("hello")
    assert not d.check("hello")
    assert "hello" not in d.suggest("helo")
    d.remove("Lozz")
    assert not d.check("Lozz")
class EnchantProxy(object):
    """Wrapper alla libreria enchant"""
    def __init__(self, mydict=None, lang='it_IT'):
        """[str] [,str]

        Ottiene l'eventuale elenco di parole personalizzate da integrare al
        dizionario ed il linguaggio da applicare - predefinito Italiano
        Solleva una eccezione se `mydict` non è accessibile
        """
        self._lang = lang
        self._custom_dict = mydict
        try:
            self._chkr = SpellChecker(lang, filters=[EmailFilter, URLFilter])
            self._pwl = DictWithPWL(lang, mydict) if mydict else None
        except enchant.errors.DictNotFoundError as nodict_err:
            raise SpellCheckError("Dizionario " + lang + " non trovato")

    def check(self, text, chunk_idx):
        """(str, int) -> list of `Error`

        Esegue il controllo per `testo` e ritorna una lista di oggetti
        `Errore` con la parola errata e la lista dei suggerimenti.
        Se la parola non viene trovata viene effettuata una ricerca anche nel
        dizionario personale (`self._pwl`) se definito
        `chunk_idx` è l'identificativo del testo da elaborare
        """
        errors = []
        self._chkr.set_text(text)
        for err in self._chkr:
            if self._pwl and self._pwl.check(err.word):
                continue
            error = Error(err.word, self._chkr.suggest(err.word), chunk_idx)
            error.context = text
            errors.append(error)
        return errors

    def upd_mydict(self, word):
        """(str)

        Aggiunge la parola `word` al dizionario personalizzato (attiva per la
        prossima chiamata a `check`.

        **L'aggiunta viene fatta solo al dizionario personalizzato IN MEMORIA
        Utilizzare `add_custom_word` per l'aggiornamento del dizionario
        personalizzato su disco**
        """
        if not self._pwl:
            return
        if self._pwl.is_added(word):
            raise SpellCheckError("Parola già esistente")
        self._pwl.add(word)

    def add_custom_words(self, words):
        """(list of str)

        Aggiunge le parole in ``words`` al dizionario personalizzato
        """
        if not self._custom_dict:
            raise SpellCheckError("Dizionario personalizzato non presente")
        orig_words = codecs.open(self._custom_dict, encoding='utf-8').split("\n")
        orig_words.extend([w for w in words if w not in orig_words])
        codecs.open(
            self._custom_dict, mode='w', encoding='utf-8'
        ).write("\n".join(orig_words))
예제 #4
0
파일: spelling.py 프로젝트: jon-turney/calm
def spellcheck_hints(args, packages):
    spelldict = DictWithPWL('en-US')
    chkr = SpellChecker(spelldict, filters=[DescFilter])
    misspellings = {}

    # add technical words not in spell-checking dictionary
    wordlist = []
    with open('words.txt') as f:
        for w in f:
            # strip any trailing comment
            w = re.sub(r'#.*$', '', w)
            # strip any whitespace
            w = w.strip()
            spelldict.add(w)
            wordlist.append(w.lower())
            # XXX: for the moment, to reduce the set of errors, ignore the fact
            # that words.txt gives a canonical capitalization, and accept any
            # capitalization
            spelldict.add(w.lower())
            spelldict.add(w.capitalize())

    # add all package names as valid words
    for p in packages:
        for w in re.split('[_-]', p):
            # remove punctuation characters
            w = re.sub(r'[+]', '', w)
            # strip off any trailing numbers
            w = re.sub(r'[\d.]*$', '', w)

            # both with and without any lib prefix
            for wl in [w, re.sub(r'^lib', '', w)]:
                # add the package name unless it exists in the list above, which
                # will give a canonical capitalization
                if wl.lower() not in wordlist:
                    spelldict.add(wl.lower())
                    spelldict.add(wl)
                    spelldict.add(wl.capitalize())

    # for each package
    for p in sorted(packages.keys()):
        # debuginfo packages have uninteresting, auto-generated text which
        # contains the package name
        if p.endswith('-debuginfo'):
            continue

        # spell-check the spell-checkable keys
        for k in ['sdesc', 'ldesc', 'message']:
            if k in packages[p].hints:
                chkr.set_text(packages[p].hints[k])
                # XXX: this is doing all the work to generate suggestions, which
                # we then ignore, so could be written much more efficiently
                for err in chkr:
                    # print("package '%s', hint '%s': Is '%s' a word?" % (p, k, err.word))
                    misspellings.setdefault(err.word, 0)
                    misspellings[err.word] += 1

    # summarize
    for c in sorted(misspellings, key=misspellings.get, reverse=True):
        print('%16s: %4d' % (c, misspellings[c]))