-
Notifications
You must be signed in to change notification settings - Fork 0
/
markov.py
95 lines (88 loc) · 2.09 KB
/
markov.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import random
import io
import json
class Markov:
try:
wordsFile = open("words.json", "+r")
vocabFile = open("vocab.json", "+r")
words = json.load(wordsFile)
vocab = json.load(vocabFile)
except:
wordsFile = open("words.json", "+w")
vocabFile = open("vocab.json", "+w")
words = []
vocab = {}
# def __init__(self):
# self.words = json.load(Markov.wordsFile)
# self.vocab = json.load(Markov.vocabFile)
#
# def readText(self, txt):
# txt = txt.split()
# try:
# for i in range(len(txt) - 1):
# try:
# self.vocab[txt[i]].append(txt[i + 1])
# except:
# self.vocab[txt[i]] = [txt[i + 1]]
# self.words.append(txt[i])
# except:
# pass
#
# def writeText(self, n = 100):
# text = [random.choice(self.words)]
# n -= 1
# try:
# for i in range(n):
# tmp = self.vocab[text[i]]
# text.append(random.choice(tmp))
# except KeyError:
# return " ".join(text)
# except IndexError as e:
# return e
# return " ".join(text)
#
# def save(self):
# Markov.wordsFile.flush();
# json.dump(self.words, Markov.wordsFile)
# Markov.vocabFile.flush();
# json.dump(self.vocab, Markov.vocabFile)
#
# def stop(self):
# self.save(self)
# self.vocabFile.close()
# self.wordsFile.close()
# print("Stopping Markov!")
def readText(txt):
txt = txt.split()
for i in range(len(txt) - 1):
try:
Markov.vocab[txt[i]].append(txt[i + 1])
except:
Markov.vocab[txt[i]] = [txt[i + 1]]
Markov.words.append(txt[i])
def save():
Markov.wordsFile.flush()
Markov.vocabFile.flush()
json.dump(Markov.words, Markov.wordsFile)
json.dump(Markov.vocab, Markov.vocabFile)
def writeText(n = 100):
text = [random.choice(Markov.words)]
n -= 1
try:
for i in range(n):
tmp = Markov.vocab[text[i]]
text.append(random.choice(tmp))
except KeyError:
print("Just a key error, nothing to see here!")
return " ".join(text)
finally:
return " ".join(text)
def stop():
Markov.save()
Markov.vocabFile.close()
Markov.wordsFile.close()
if __name__ == "__main__":
text = """test"""
Markov.readText(text)
print(Markov.writeText())
#test