view bitsyauth/dictionary.py @ 56:d09682c9cd98 default tip

skimpyGimpy aint python3
author Jeff Hammel <k0scist@gmail.com>
date Tue, 03 Nov 2020 13:31:30 -0800
parents d4522af2c6e5
children
line wrap: on
line source

import random

class Dictionary(object):
    def __init__(self, dictionary_file='/usr/share/dict/american-english'):
        self.dictionary_file = dictionary_file
        with open(dictionary_file) as f:
            self.wordlist = []
            for line in f:
                line = line.strip()
                if not line or not line.isalpha():
                    continue
                line = line.lower()
                self.wordlist.append(line)
            self.wordlist = tuple(self.wordlist)
        self._min_lengths = {}

    def random_word(self, min_length=5):
        """
        choose random word

        min_length -- minimum word length
        """

        if min_length not in self._min_lengths:
            # cache
            self._min_lengths[min_lengths] = [i for i in self.wordlist
                                              if len(i) > min_length]
        return random.Random().choice(self._min_lengths[min_length])