markov3_use.py

from __future__ import print_function

#
# Generate a non-sensical sentence using bigram
#
def compose(m1, m2, count=10):
    from markov3_io import shift
    import random
    first_word = random.choice(list(m1.keys()))
    second_word = random.choice(m1[first_word])
    prefix = (first_word, second_word)
    print(first_word, second_word, end=' ')
    for n in range(2, count):
        next_word = random.choice(m2[prefix])
        print(next_word, end=' ')
        prefix = shift(prefix, next_word)
    print()

def compose_from(path, count=10):
    from markov3_io import read_grams
    m1, m2 = read_grams(path)
    compose(m1, m2, count)

try:
    compose_from('bee.txt')
except IOError as e:
    print("compose error: missing file: %s" % e)
except KeyError as e:
    print("compose error: illegal prefix: %s" % e)