-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkov.py
141 lines (117 loc) · 3.65 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# -*- coding: utf-8 -*-
import MeCab
import re
import random
import json
class Word:
def __init__(self, deep, maxi):
self.deep = deep
self.count = 0
self.nexts = {}
self.MAXI_CHAIN = maxi
def add(self, words):
self.count += 1
if len(words) < 1:
return
if len(words) < self.MAXI_CHAIN - self.deep - 1:
return
w = words.pop(0)
if self.deep < self.MAXI_CHAIN - 1:
if w not in self.nexts:
self.nexts[w] = Word(self.deep+1, self.MAXI_CHAIN)
self.nexts[w].add(words)
def show(self):
text = ""
for w in self.nexts:
blank = ""
for _ in range(self.deep):
blank += " "
text += blank + w + "[" + str(self.nexts[w].deep) + \
" / " + str(self.nexts[w].count) + "]"
if self.deep < self.MAXI_CHAIN - 1:
text += " -> " + self.nexts[w].show() + "\n"
return text
def pick(self):
r = random.randrange(self.count)
cnt = 0
for k, n in self.nexts.items():
cnt += n.count
# print(f"{cnt} -> {r}/{self.count}")
if r < cnt:
# print(f"HIT")
return k
raise Exception("Tree Counter is broken.")
def write(self, cnt=0):
for key, val in self.nexts.items():
cnt = val.write(cnt+1)
return cnt
def json_format(self):
dic = {}
dic["count"] = self.count
dic["children"] = {}
for k, v in self.nexts.items():
dic[k] = self.nexts[k].json_format()
return dic
class MarkovTree:
def __init__(self, dic, maxi=3):
self.root = Word(-1, maxi)
self.MAXI_CHAIN = maxi
self.dic = dic
def add_tree(self, data):
words = ["[START]"]
words.extend(self.separate(data))
# words[-1] = "[END]"
words.append("[END]")
self.make_chain(words)
def make_chain(self, words_list):
for i in range(len(words_list)):
self.root.add(words_list[i:])
def separate(self, data):
mecab = MeCab.Tagger(self.dic)
# mecab = MeCab.Tagger()
mecab.parse("")
m = mecab.parse(data)
lines = m.split("\n")
words = []
for line in lines:
words.append((re.split('[\t,]', line)[0]))
for _ in range(2):
words.pop() # 最後の謎の空白2こを削除
return words
def create(self, sentencelist):
for s in sentencelist:
# s = f.read()
# s = self.cut_unneccesarry(s)
# s = self.replace_spletters(s)
self.add_tree(s)
def write(self):
self.root.write(0)
def json_format(self):
return self.root.json_format()
def get_markov(dic, data, num=1):
tree = MarkovTree(dic)
# tree = MarkovTree(dic, 2)
with open(data) as f:
sentencelist = f.read().split("\n")
tree.create(sentencelist)
tree.write()
print(json.dumps(tree.json_format(), ensure_ascii=False))
results = []
for _ in range(num):
lis = []
fst = "[START]"
# tree.root.nexts[fst].show()
snd = tree.root.nexts[fst].pick()
lis.append(snd)
while snd != "[END]":
# snd = tree.root.nexts[snd].pick()
# lis.append(snd)
newsnd = tree.root.nexts[fst].nexts[snd].pick()
lis.append(newsnd)
fst = snd
snd = newsnd
lis.pop()
results.append("".join(lis))
return "\n".join(results)
if __name__ == "__main__":
print(get_markov("sing.tb", 20))