Last active
July 12, 2019 23:17
-
-
Save gzomer/18476088ea3c2992f67f6c8bc04d8e3a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def build_markov_chain(data, n): | |
chain = { | |
'_initial':{}, | |
'_names': set(data) | |
} | |
for word in data: | |
word_wrapped = str(word) + '.' | |
for i in range(0, len(word_wrapped) - n): | |
tuple = word_wrapped[i:i + n] | |
next = word_wrapped[i + 1:i + n + 1] | |
if tuple not in chain: | |
entry = chain[tuple] = {} | |
else: | |
entry = chain[tuple] | |
if i == 0: | |
if tuple not in chain['_initial']: | |
chain['_initial'][tuple] = 1 | |
else: | |
chain['_initial'][tuple] += 1 | |
if next not in entry: | |
entry[next] = 1 | |
else: | |
entry[next] += 1 | |
return chain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment