#!/usr/bin/python # # Installation: # gunzip TWL.gz # edit TWL_PATH to contain the path to the TWL file # # Sample usage: # # I want to align the word "roux" with "pina", if possible. # echo roux | align pina # # I want to align a word made of the letters [srttoih] with the beginning of # a word that begins with "pneu" # anagram srttoih | align pneu00000 # ... and sort it so the highest-scoring words are at the bottom # anagram srttoih | score | sort -n | cut -f 2 | align pneu00000 import sys TWL_PATH = "/Path/To/TWL" # Filter a list def filter(fn, list): return [ item for item in list if fn(item) ] # Normalizes a line read from a file def normalize(line): return line.strip("\n").lower() # Prints 'indent' spaces and then the string 'str' def tab(str, indent): return str.rjust(len(str) + indent) # Given an alignment as a tuple (e.g. ('foo', ' bar')) return true if # all the cross-words are valid two-letter words def valid_alignment(alignment, twos): (top, bottom) = alignment for i in range(0, min(len(top), len(bottom))): if (not top[i] == ' ' and not bottom[i] == ' ' and "%c%c" % (top[i], bottom[i]) not in twos): return False return True # Tries to find ways where "top" can legally line up over "bottom" def maybe_align(top, bottom, twos): # First, generate a list containing all possible alignments as tuples # This includes ('foo', ' bar'), ('foo', ' bar'), etc. alignment_list = [(top, bottom)] for top_indent in range(1, len(bottom)): alignment_list.append((tab(top, top_indent), bottom)) for bottom_indent in range(1, len(top)): alignment_list.append((top, tab(bottom, bottom_indent))) for alignment in filter(lambda x: valid_alignment(x, twos), alignment_list): print "\n%s\n%s" % alignment # Main --- # User input: the word to align aligner = normalize(sys.argv[1]) # Find the list of two-letter words twl = map(normalize, file(TWL_PATH).readlines()) twos = filter(lambda x: len(x) == 2, twl) # User input (stdin): the words to align against 'aligner' for alignee in sys.stdin: alignee = normalize(alignee) maybe_align(alignee, aligner, twos) # alignee on top maybe_align(aligner, alignee, twos) # aligner on top