Last active
November 20, 2024 19:17
-
-
Save zamora/3e385e0387a5d43047f3110d6c9dcd1a to your computer and use it in GitHub Desktop.
Solve The Washington Post's Keyword game
This file contains hidden or 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/python3 | |
# | |
# wapo-keyword.py | |
# | |
# Program to solve The Washington Post's Keyword game. | |
# https://www.washingtonpost.com/games/keyword | |
# | |
# Usage: Enter the words on the command line, using a period for the | |
# missing letters. | |
# | |
# Example: keyword.py .nsist ba. pro.ane st.ut sto.e clai. | |
import sys | |
import re | |
# Although you can use /usr/dict/words as a list of possible words, | |
# it is missing many words and forms. I created my own custom wordlist | |
# based on /usr/share/dict/words and the 2019 Scrabble dictionary, with all | |
# characters converted to lowercase, Unicode characters converted to ASCII, | |
# and proper nouns and possessive's removed. | |
# wordlist = "/usr/share/dict/words" | |
wordlist = "wordlist.txt" | |
classes = "^" # Anchor the pattern to the beginning of the line | |
# Build the character classes for each input word | |
for word in sys.argv[1:]: | |
# Get the position of the missing letter | |
pos = word.index('.') | |
pattern = re.compile("^"+word+"$") | |
# Find all words that match the pattern | |
results = [] | |
with open(wordlist,'r') as dict: | |
for word in dict: | |
result = pattern.findall(word) | |
if result: | |
results.extend(result) | |
# Make a character class of all the possible missing letters. | |
charclass = "[" | |
for str in results: | |
charclass += str[pos] | |
charclass += "]" | |
classes += charclass | |
classes += "$" # Anchor the pattern to the end of the line | |
# Use the constructed character classes to search for the answer | |
# in the wordlist. | |
results = [] | |
pattern = re.compile(classes) | |
with open(wordlist,'r') as dict: | |
for word in dict: | |
result = pattern.findall(word) | |
if result: | |
results.extend(result) | |
# Display the solution | |
print(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment