Last active
August 29, 2015 14:19
-
-
Save oskar456/39843d3282653f0064af to your computer and use it in GitHub Desktop.
Find a word that consists of certian letters in dictionary (a.k.a. 4 Pics 1 Word helper)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import collections | |
import re | |
parser = argparse.ArgumentParser( | |
description='Find a word consisting of certain letters in dictionary' | |
) | |
parser.add_argument('letters', | |
help="letters to choose from" | |
) | |
parser.add_argument('-l', '--length', | |
help="length of the word", | |
type=int | |
) | |
parser.add_argument('-d', '--dictionary', | |
help="path to dictionary, default %(default)s", | |
default="/usr/share/dict/words" | |
) | |
parser.add_argument('-m', '--mask', | |
help="regular expression to mask found words, eg. '...e.s'" | |
) | |
args = parser.parse_args() | |
chars = collections.defaultdict(int) | |
for ch in args.letters.lower(): | |
chars[ch] += 1 | |
if args.mask: | |
mask = re.compile(args.mask, re.I) | |
with open(args.dictionary, 'r') as inf: | |
for word in (w.strip() for w in inf): | |
if ((args.length and len(word) != args.length) or | |
(args.mask and not mask.match(word))): | |
continue | |
my_chars = dict(chars) | |
for ch in word.lower(): | |
if ch in my_chars and my_chars[ch]>0: | |
my_chars[ch] -= 1 | |
else: | |
break | |
else: | |
print(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment