Create an acrostic

Python 2.7

import random
import string
import sys
import re

class Markov(object):
    def __init__(self,filename):
        with open(filename,'r') as f:
            self._words = f.read().split()
            self._wordCount = len(self._words)

    def getWordList(self,seedWord=None,pattern=r'^.*$'):
        if seedWord is not None:
            chainWords = [self._words[i+1] for i in range(self._wordCount-1)\
                if seedWord == self._words[i].lower()]
        else:
            chainWords = self._words
        p = re.compile(pattern,re.IGNORECASE)
        return filter(p.match,chainWords)

    def getRandWord(self,seedWord=None,pattern=r'^.*$'):
        wordList = self.getWordList(seedWord,pattern)
        if len(wordList) == 0:
            return None
        return random.choice(self.getWordList(seedWord,pattern))

def main():
    list = Markov('AStudyInScarlet.txt')
    for word in sys.argv[1:]:
        poem = []
        for letter in word:
            if len(poem) == 0:
                nextWord = list.getRandWord(pattern=r'^[{0}.*$]'.format(letter))
            else:
                nextWord = list.getRandWord(poem[-1],r'^{0}.*$'.format(letter))
                if nextWord is None:
                    nextWord = list.getRandWord(pattern=r'^{0}.*$'.format(letter))
            nextWord = ''.join(ch for ch in nextWord if ch not in string.punctuation)
            poem.append(nextWord)

        print word
        print '='*len(word)
        for line in poem:
            print line
        print ''

if __name__ == '__main__':
    main()

Loads a text file called 'AStudyInScarlet.txt'. Only words used in that document will be candidates for incorporation into the final poem. (currently there are no words starting with x in this document, I will add some soon)

This program tries to find words in the text file that follow the previous word in the poem. For example, if the acrostic word is 'pita' and so far the poem is "Private," a possible next word is "inquiry" as the two word phrase "private inquiry" is found in the text document. If no matching word pairs are found, any random word starting with the right letter is chosen.

A word is chosen from a list of words that meet the desired qualifications. If a word shows up multiple times in the list of acceptable words, it is more likely to be chosen than one that does not.

Usage

Words to create poems from should be specified as command line arguments. One poem will be printed for each word specified on the command line.

Example:

$ acrostic.py laughable codegolf loremipsum
laughable
=========
Looking
a
Union
grievous
his
agitation
be
likely
enough

codegolf
========
couple
of
discoloured
evident
goes
or
late
from

loremipsum
==========
learn
of
revenge
engine
me
it
proved
smartest
up
my

PHP

<?php
$dict = array(
    'a' => 'and',
    'i' => 'if',
    'o' => 'or',
    'n' => 'not',
    'l' => 'list'
);
$funcs = get_defined_functions();
$word = rtrim(fgets(STDIN), "\n");
echo "\n";
foreach(str_split($word) as $char)
    foreach($dict + $funcs['internal'] as $func)
        if($func[0] == $char){
            echo $func . "\n";
            break;
        }

I admit it does not always make sense, but I am too lazy to look for a real word list, so I used PHP function names plus a couple of PHP reserved words.

Examples:

laughable

list
and
user_error
get_class
hash
and
bzopen
list
each

codegolf

class_exists
or
define
each
get_class
or
list
func_num_args

loremipsum

list
or
restore_error_handler
each
method_exists
if
property_exists
strlen
user_error
method_exists

neurotic

not
each
user_error
restore_error_handler
or
trigger_error
if
class_exists

diplomat

define
if
property_exists
list
or
method_exists
and
trigger_error