from random import choice #allows choice in getnext to chose at random
import sys
def generateModel(text, order): #funtion called generate moddel
model = {} #curly braces in python to define a dictionary
for i in range(0, len(text) – order): #if text is bobby, len is 5, if order is 3,
#5-3 is 2 so the last fragment considered below will be bby(2,3,4) (0-4 is 5 letters)
fragment = text[i:i+order] #i+order so it takes that many letters? bo as frag
#apparently i:i+order starts from i and stops at i+order WITHOUT including it
#so with order = 1, and text = bobby, first fragment will be just b.
next_letter = text[i+order] #the next letter will be i+order. o is next
if fragment not in model:
model[fragment] = {} #if b is first it’s not in model yet so nothing is added
#also more curly braces so this is the inner dictionary
#also square brackets add a value to the dictionary.
if next_letter not in model[fragment]:
model[fragment][next_letter] = 1 #model adds o as a next letter to b and if not
#in model it is assigned a weight of 1
else:
model[fragment][next_letter] += 1 #if either frag or next are letter already in
#the model then the number is incremented.
return model
def getNextCharacter(model, fragment):#so I guess „fragment will be from generate model“
letters = []
for letter in model[fragment].keys():#will look through each fragment and for each key in that fragment…
for times in range(0, model[fragment][letter]):#…the range will be set by the number given to the key
letters.append(letter)#so for the bobby example, b of b is 1 and so it appends b and breaks
return choice(letters)#choice after all the loops will be a random choice out of letters
def generateText(text, order, length):
model = generateModel(text, order)#calls generate model
currentFragment = text[0:order]#again 0:order is up to but not including that index
output = „“#
for i in range(0, length-order):
newCharacter = getNextCharacter(model, currentFragment)#gets weighted random character
output += newCharacter #adds it to output
currentFragment = currentFragment[1:] + newCharacter
print output#change to [1:] above means truncating the character at 0: so you can
#add + newCharacter to fill the fragment again before looping
text = „some sample text“
if __name__ == „__main__“: #a main check because the itrpter names a module main
#if it is running as it’s own program
#if someone wanted to use the module in another program
#and call the functions themselves the ifstatement ensures
#the module doesn’t run when accessed.
generateText(text, int(sys.argv[1]), int(sys.argv[2]))
# sys.argv 1 and 2 are what I will pass on running the
#program(text doesn’t need to be passed as it will be defined
#the code. it’s as simple as markov.py 2 5 (2 and 5 being
#order and length respectivly.