Homework 4 – Modules and Functions

For this assignment, I modularized my Midterm assignment and put the relevant chunks of code into functions within a module.  The simplest thing to do was to just wrap stuff up in functions, but the value of functions is make code both reusable and flexible.  After looking at my code for a while, the only real flexibility I could add was to allow for substituting different kinds of word substitution – i.e. synonyms, or antonyms, or hyponyms, etc.

So my code went from being pretty bloated, to fundamentally coming down to one line, that is called like so:

from synonymize import synonymize

poem = synonymize('I am a dummy line of text', 'synonym')

Meaning I can pass any line of text into it as well as the type of substitution, and I’ll get back my poem in a list.  Since it’s a list, there are a few extra lines that handle printing out the lines nicely, but the heart of the program is now extremely simple.  The module, however, is pretty messy, and looks like this:

from random import choice
from wordnik import *
apiUrl = 'http://api.wordnik.com/v4'
apiKey = '********' 
client = swagger.ApiClient(apiKey, apiUrl)
wordApi = WordApi.WordApi(client)

# Get synonyms for every word from wordnik
# Pass a list of words, return dictionary of synonyms for each word
# using wordnik API
# acceptable relationship types:
#   synonym, antonym, hyponym, some others
def relationship_dict(word_list, relationship='synonym'):
    synonyms = {}
    if len(word_list) == 0:
        return {}
    for word in word_list:
        syn = wordApi.getRelatedWords(word, relationshipTypes=relationship, useCanonical='true')
            # Save list of synonyms into dict with words as the key
            synonyms[word] = syn[0].words
        except TypeError: 
            # If no synonyms were found, save in an empty list
            synonyms[word] = []

    return synonyms

# Break an array of words into the structure
# of the poem - i.e. each successive line
# has one ore word
def create_structure(word_array):
    structured_list = []
    for i in range(len(word_array)):
    return structured_list

# Line constructor - give it a line, 
# and a dictionary of words to substitute, 
# and it'll randomly replace
def construct_line(line, word_subs):
    word_counter = 0
    for word in line:
            rand_sub = choice(word_subs[word])
            # if there's no substitute, just return the same word
            rand_sub = word
        line[word_counter] = rand_sub
        word_counter += 1

    return line

# Master function - creates the poem
def synonymize(line, relationship='synonym'):
    word_array = line.split()
    # Create structure of poem
    all_lines = create_structure(word_array)

    # Create relationship words dictionary
    relationshipDict = relationship_dict(word_array, relationship)

    # Construct lines, one at a time
    line_counter = 0
    for l in all_lines:
        # print l
        l = construct_line(l, relationshipDict)
        # print l
        all_lines[line_counter] = construct_line(l, relationshipDict)
        line_counter += 1

    return all_lines    

The module provides functionality to create a dictionary of related words given a string of words and a substituion type. A function to generate the structure of the poem – i.e. each new line has one more word. And a function to do substitution on a single line. These are all then called within a master function, synonymize() which spits out the poem.

The output is still just as terrible….


Adventurous dogs amaze me. This morning my dog yelped because he unexpectedly stepped on a shipping bag. =\
        foolhardy qualifier
            restless andiron perplex
                foolhardy dude astonish mine
                    hazardous bloke perplex my This
                        dangerous chap perplex I This morningtide
                            hazardous man amazement my ass This morn my
                                dangerous andiron astound us This morrow mine andiron
                                    daring fellow bewilder I This forenoon my dude boast
                                        hazardous chap confound my ass This morrow mine dude yaup forwhy
                                            foolhardy fellow astonish myself This morningtide mine dude yaup forwhy it
                                                dangerous wretch amazement myself This forenoon mine man yaup ask they unexpectedly
                                                    hazardous firedog perplex myself This morrow mine fellow yaup ask man unexpectedly stepped
                                                        dangerous firedog perplex my ass This forenoon my fellow boast inasmuch as his ass unexpectedly stepped concerning
                                                            hazardous dude bewilder myself This morningtide mine man yelped since s/he unexpectedly stepped concerning ongoing
                                                                enterprising man surprise us This morrow mine man boast ask qualifier unexpectedly stepped onward adhering ships
                                                                    hazardous chap bewilder us This morningtide mine firedog yaup for informal unexpectedly stepped about of navigation sack
                                                                        restless guy confound my This morrow mine andiron boast long her ass unexpectedly stepped of a navigation swell invalid

Leave a Reply

Your email address will not be published. Required fields are marked *