|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Crossword helper""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import os |
| 6 | +import re |
| 7 | +import sys |
| 8 | +from typing import List, TextIO |
| 9 | + |
| 10 | + |
| 11 | +# -------------------------------------------------- |
| 12 | +def get_args() -> argparse.Namespace: |
| 13 | + """Get command-line arguments""" |
| 14 | + |
| 15 | + parser = argparse.ArgumentParser( |
| 16 | + description='Crossword helper', |
| 17 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| 18 | + |
| 19 | + parser.add_argument('pattern', metavar='str', help='The pattern to search') |
| 20 | + |
| 21 | + parser.add_argument('-w', |
| 22 | + '--wordlist', |
| 23 | + help='Wordlist to search', |
| 24 | + metavar='str', |
| 25 | + type=argparse.FileType('r'), |
| 26 | + default='/usr/share/dict/words') |
| 27 | + |
| 28 | + return parser.parse_args() |
| 29 | + |
| 30 | + |
| 31 | +# -------------------------------------------------- |
| 32 | +def regex_solution(pattern: str, wordlist: TextIO) -> List[str]: |
| 33 | + """Using regular expressions""" |
| 34 | + |
| 35 | + regex = r'\b{}\b'.format(pattern.replace('_', '.')) |
| 36 | + return re.findall(regex, wordlist.read()) |
| 37 | + |
| 38 | + |
| 39 | +# -------------------------------------------------- |
| 40 | +def manual_solution(pattern: str, wordlist: TextIO) -> List[str]: |
| 41 | + """Not using regular expressions""" |
| 42 | + |
| 43 | + letters = [t for t in enumerate(pattern) if t[1] != '_'] |
| 44 | + #letters = filter(lambda t: t[1] != '_', enumerate(pattern)) |
| 45 | + wanted_len = len(pattern) |
| 46 | + words = [] |
| 47 | + |
| 48 | + for word in wordlist.read().split(): |
| 49 | + if len(word) == wanted_len and all( |
| 50 | + [word[i] == char for i, char in letters]): |
| 51 | + words.append(word) |
| 52 | + |
| 53 | + return words |
| 54 | + |
| 55 | + |
| 56 | +# -------------------------------------------------- |
| 57 | +def main(): |
| 58 | + """Make a jazz noise here""" |
| 59 | + |
| 60 | + args = get_args() |
| 61 | + words = regex_solution(args.pattern, args.wordlist) |
| 62 | + #words = manual_solution(args.pattern, args.wordlist) |
| 63 | + |
| 64 | + if words: |
| 65 | + for i, word in enumerate(words, start=1): |
| 66 | + print('{:3}: {}'.format(i, word)) |
| 67 | + else: |
| 68 | + print('Found no words matching "{}".'.format(args.pattern)) |
| 69 | + |
| 70 | + |
| 71 | +# -------------------------------------------------- |
| 72 | +if __name__ == '__main__': |
| 73 | + main() |
0 commit comments