from __future__ import print_function
#
# Read prefix-suffix maps for a file
#
def read_grams(path):
import shelve
s = shelve.open(path)
h1 = s["h1"]
h2 = s["h2"]
s.close()
return h1, h2
#
# Generate a non-sensical sentence using bigram
#
def compose(h1, h2, count=10):
import random
first_word = random.choice(list(h1.keys()))
second_word = random.choice(h1[first_word])
prefix = (first_word, second_word)
print(first_word, second_word, end=' ')
for n in range(2, count):
next_word = random.choice(h2[prefix])
print(next_word, end=' ')
prefix = shift(prefix, next_word)
print()
def shift(prefix, word):
return prefix[1:] + (word,)
def compose_from(path, count=10):
h1, h2 = read_grams(path)
compose(h1, h2, count)
compose_from('bee.shelf')