repl.it
@simontiger/

Markov Text

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import random

text = ""

print("Type your text here (type END to end it):")

while True:
  line = input("")
  if line != "END": text += line + "\n"
  else: break

text = text[:len(text)-1]

order = int(input('Type the order (how much it makes sense) here: '))
num = int(input("Type the number of characters here: "))

input("Generate me a beautiful text")

def markov_blanket(text, order):
  result = {}

  for i in range(len(text) - order + 1):
    ngram = ""
    for off in range(order):
      ngram += text[i+off]
    
    if not ngram in result:
      result[ngram] = []
    if i < len(text) - order:
      result[ngram].append(text[i+order])
  
  return result

def markov_chain(blanket, num):
  keys = blanket.keys()
  ngram = random.choice(list(keys))
  new_text = ngram
  for i in range(num):
    try:
      nxt = random.choice(blanket[ngram])
      new_text += nxt
      ngram += nxt
      ngram = ngram[1:]
    except IndexError:
      break
  return new_text

new_text = markov_chain(markov_blanket(text, order), num)
print(new_text)