Created
August 16, 2017 17:10
-
-
Save Zagrebelin/75a4eff41bd3d72c01e0131769f80141 to your computer and use it in GitHub Desktop.
simplest markov chain realisation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from collections import defaultdict, Counter | |
def build_chain(words): | |
""" build Markov chain from the list of words """ | |
chain = defaultdict(Counter) | |
for idx, current_word in enumerate(words[:-1]): | |
next_word = words[idx+1] | |
chain[current_word].update([next_word]) | |
return chain | |
def generate(chain, length): | |
""" generate new text given length from the chain """ | |
current_word = random.choice(list(chain.keys())) | |
ret = [current_word] | |
for _ in range(length): | |
next_pairs = chain[current_word].items() | |
next_words, weights = list(zip(*next_pairs)) | |
current_word = random.choices(next_words, weights)[0] | |
ret.append(current_word) | |
return ' '.join(ret) | |
chain = build_chain('вот так вот все и было вот так'.split()) | |
print(chain) | |
print(generate(chain, 4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment