06-25-2015, 05:38 AM
(This post was last modified: 06-25-2015, 04:54 PM by ddthj.
Edit Reason: Fixed a small bug that causes first time words to be skipped when regestering first time words :P
)
So I spent 3 hours making a messy markov chain generator in python, and since it was a pain to do I figured I'd post it here so no one else has to go through the trouble
This takes a text input prompt but you could use any method to give it text.
The generator keeps track of:
words,
what words come after other words,
the amount of times a word has come after another word.
Brain format:
brain{ word :[ [other word, times found], [other word, times found] ], word :[ [other word, times found], [other word, times found] ] }
kindof a mess, but hey if it works it works :)
This takes a text input prompt but you could use any method to give it text.
The generator keeps track of:
words,
what words come after other words,
the amount of times a word has come after another word.
Brain format:
brain{ word :[ [other word, times found], [other word, times found] ], word :[ [other word, times found], [other word, times found] ] }
kindof a mess, but hey if it works it works :)
Code:
brain = {} #making the main dict
text = input('Please enter a sentence.\n') #getting some text
text = text.lower() #making the text less variable
words = text.split(' ') #splitting the text into words
wordlen = len(words) #finding the number of words
print(words)
print(wordlen)
itemcount = 0
for item in words:
hit = False
if itemcount >= len(words)-1: #making sure we don't loop through the last word because that will throw an error
break
if item in brain: # if the item already exists, we do this:
nextitem = words[int(itemcount)+1] #find the word after this one
b = brain[str(item)] #make a name for the list of words that come after the current word we are on
for mylist in b:
if str(mylist[0]) == str(nextitem): #check to ensure we don't duplicate a word
count = int(mylist[1]) #if the following word already exists, we add 1 to the number of times it has appeared after the current word in question
count += 1
mylist[1] = count
hit = True
if hit == False: #if we have never seen it come after the current word, we add it
newlist = [str(nextitem), 1]
b.append(newlist)
else: #for when the item doesn't already exist
brain[str(item)] = [] #make the item
nextitem = words[int(itemcount)+1]
b = brain[str(item)]
for mylist in b: #go through same process as before with finding words that come after it
if str(mylist[0]) == str(nextitem):
count = int(mylist[1])
count += 1
mylist[1] = count
hit = True
if hit == False:
newlist = [str(nextitem), 1]
b.append(newlist)
itemcount+=1
print(str(brain))