Skip to content

Instantly share code, notes, and snippets.

@zesterer
Created July 31, 2018 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zesterer/748fd0e8b8f7784c7709dfc3d50a58b0 to your computer and use it in GitHub Desktop.
Save zesterer/748fd0e8b8f7784c7709dfc3d50a58b0 to your computer and use it in GitHub Desktop.
4th Order Markov Chain Generator
import random
by_word = True
text = open("test.txt").read().replace(" ", " ")
if by_word:
text = text.split(" ")
freq = {}
p3 = ' '
p2 = ' '
p1 = ' '
p = ' '
for c in text:
if not p3 in freq:
freq[p3] = {}
if not p2 in freq[p3]:
freq[p3][p2] = {}
if not p1 in freq[p3][p2]:
freq[p3][p2][p1] = {}
if not p in freq[p3][p2][p1]:
freq[p3][p2][p1][p] = {}
if not c in freq[p3][p2][p1][p]:
freq[p3][p2][p1][p][c] = 0
freq[p3][p2][p1][p][c] += 1
p1 = p
p = c
#print(freq)
s = ""
c3 = random.choice(list(freq.keys()))
c2 = random.choice(list(freq[c3].keys()))
c1 = random.choice(list(freq[c3][c2].keys()))
c = random.choice(list(freq[c3][c2][c1].keys()))
for i in range(0, 2000):
t = sum(list(freq[c3][c2][c1][c].values()))
r = random.randint(0, t)
for l, v in freq[c3][c2][c1][c].items():
if r < v:
s += l + (" " if by_word else "")
c1 = c
c = l
break
else:
r -= v
print(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment