#!/usr/bin/env python3 # -*- coding: utf-8 -*- """https://xkcd.com/936/""" # Copyright (c) 2016 Karl Fogel. Released under MIT open source license: # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import os import re import sys import getopt import random def import_word_source(source, dest): """Import words from SOURCE as keys into dictionary DEST. SOURCE is a file containing words, one per line. When a word ends in "'s" or has other common undesirable elements, either that element will be removed before the word is stored into DEST, or the word will not be stored at all. Words are also always downcased. The values in DEST are undefined and should be ignored.""" with open(source, "r", encoding="utf-8", errors="backslashreplace") as f: for word in f: word = word.strip() if word == "" or word.find(" ") != -1: continue elif word[-2:] == "'s": word = word[:-2] word = word.lower() dest[word] = True def main(): word_sources = [ "/usr/share/dict/words", os.path.expanduser("~/.aspell.en.pws") ] words = { } for source in word_sources: import_word_source(source, words) # Convert words to an array, for random access. words = list(words.keys()) randy = random.SystemRandom() # Display the results in a regular grid. rows = 20 cols = 4 output = [[None for x in range(cols)] for y in range(rows)] maxlen = 0 for row in range(rows): for col in range(cols): word = randy.choice(words) import unicodedata # len() will get byte length, not character length, so non-ASCII # words can mess up output alignment. This isn't necessarily a # bug, and isn't necessarily not a feature either. maxlen = max(maxlen, len(word)) output[row][col] = word for row in range(rows): for col in range(cols): sys.stderr.write(output[row][col].ljust(maxlen + 2)) sys.stderr.write("\n") if __name__ == '__main__': main()