Markov chain text generator: Difference between revisions

Content added Content deleted
(→‎{{header|REXX}}: optimized the building of the prefix table.)
(Edited my Python to conform to standards a bit better.)
Line 842: Line 842:
import random
import random



#Read a file and return its contents.
def readdata(file):
def readdata(file):
'''Read file and return contents.'''
with open(file) as f:
with open(file) as f:
contents = f.read()
contents = f.read()
return contents
return contents



#Make a markov rule for given data.
def makerule(data, context):
def makerule(data, context):
'''Make a rule dict for given data.'''
rule = {}
rule = {}
words = data.split(' ')
words = data.split(' ')
Line 864: Line 866:
return rule
return rule



#Use a markov rule to create a string.
def makestring(rule, length):
def makestring(rule, length):
'''Use a given rule to make a string.'''
oldwords = random.choice(list(rule.keys())).split(' ')#random starting words
oldwords = random.choice(list(rule.keys())).split(' ') #random starting words
string = ' '.join(oldwords) + ' '
string = ' '.join(oldwords) + ' '
Line 883: Line 886:
return string
return string



#Main program
if __name__ == '__main__':
data = readdata(sys.argv[1])
rule = makerule(data, int(sys.argv[2]))
data = readdata(sys.argv[1])
string = makestring(rule, int(sys.argv[3]))
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)</lang>
print(string)</lang>


{{out}}
{{out}}