-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkov_chain_text.py
46 lines (36 loc) · 1.31 KB
/
markov_chain_text.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
# Program to generate text from given text using markov chain
import random
import string
word_graph = {}
def main():
# Save words of text into an array
file_path = (input("Enter file path: "))
words = []
with open(file_path, "r") as f:
for line in f:
for w in line.split():
w.lower().translate(str.maketrans('', '', string.punctuation))
words.append(w)
# Transfer words to a graph
for i, curr in enumerate(words[:-1]):
next = words[i + 1]
if curr in word_graph.keys():
word_graph[curr][next] = word_graph[curr].get(next, 0) + 1
else:
word_graph[curr] = {next: 1}
# Generate text
word_count = int(input("Enter length of generated text: "))
# Choose random starting word in dict
curr = random.choice(list(word_graph.keys()))
for _ in range(word_count):
print(curr, end=" ")
next_words_dict = word_graph[curr]
if next_words_dict:
next_words = list(next_words_dict.keys())
weights = list(next_words_dict.values())
curr = random.choices(next_words, weights)[0]
else:
curr = random.choice(list(word_graph.keys()))
print()
if __name__ == "__main__":
main()