Permalink
Browse files

This program generates the wordPatterns.py module.

  • Loading branch information...
1 parent 1c9d47f commit 0a8a95375ebc198a1f5daeb93033e75ece0cfc37 @asweigart committed Feb 1, 2013
Showing with 52 additions and 0 deletions.
  1. +52 −0 makeWordPatterns.py
View
@@ -0,0 +1,52 @@
+# Makes the wordPatterns.py File
+# http://inventwithpython.com/hacking (BSD Licensed)
+
+# Create wordPatterns.py based on the words in our dictionary
+# text file, dictionary.txt. (Download this file from
+# http://invpy.com/dictionary.txt)
+
+import pprint
+
+
+def getWordPattern(word):
+ # Returns a string of the pattern form of the given word.
+ # e.g. '0.1.2.3.4.1.2.3.5.6' for 'DUSTBUSTER'
+ word = word.upper()
+ nextNum = 0
+ letterNums = {}
+ wordPattern = []
+
+ for letter in word:
+ if letter not in letterNums:
+ letterNums[letter] = str(nextNum)
+ nextNum += 1
+ wordPattern.append(letterNums[letter])
+ return '.'.join(wordPattern)
+
+
+def main():
+ allPatterns = {}
+
+ fp = open('dictionary.txt')
+ wordList = fp.read().split('\n')
+ fp.close()
+
+ for word in wordList:
+ # Get the pattern for each word in wordList.
+ pattern = getWordPattern(word)
+
+ if pattern not in allPatterns:
+ allPatterns[pattern] = [word]
+ else:
+ allPatterns[pattern].append(word)
+
+ # This is code that writes code. The wordPatterns.py file contains
+ # one very, very large assignment statement.
+ fp = open('wordPatterns.py', 'w')
+ fp.write('allPatterns = ')
+ fp.write(pprint.pformat(allPatterns))
+ fp.close()
+
+
+if __name__ == '__main__':
+ main()

0 comments on commit 0a8a953

Please sign in to comment.