Skip to content

Instantly share code, notes, and snippets.

@benhoyt
Created November 11, 2023 15:45
Show Gist options
  • Save benhoyt/619cf3113866450aa31d8a2c1f8e01dc to your computer and use it in GitHub Desktop.
Save benhoyt/619cf3113866450aa31d8a2c1f8e01dc to your computer and use it in GitHub Desktop.
Generate text from an input using a simple Markov chain generator
import collections, random, sys, textwrap
# Build possibles table indexed by pair of prefix words (w1, w2)
w1 = w2 = ''
possibles = collections.defaultdict(list)
for line in sys.stdin:
for word in line.split():
possibles[w1, w2].append(word)
w1, w2 = w2, word
# Avoid empty possibles lists at end of input
possibles[w1, w2].append('')
possibles[w2, ''].append('')
# Generate randomized output (start with a random capitalized prefix)
w1, w2 = random.choice([k for k in possibles if k[0][:1].isupper()])
output = [w1, w2]
for _ in range(int(sys.argv[1])):
word = random.choice(possibles[w1, w2])
output.append(word)
w1, w2 = w2, word
# Print output wrapped to 70 columns
print(textwrap.fill(' '.join(output)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment