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 |
||
⚫ | |||
def readdata(file): |
def readdata(file): |
||
⚫ | |||
with open(file) as f: |
with open(file) as f: |
||
contents = f.read() |
contents = f.read() |
||
return contents |
return contents |
||
⚫ | |||
def makerule(data, context): |
def makerule(data, context): |
||
⚫ | |||
rule = {} |
rule = {} |
||
words = data.split(' ') |
words = data.split(' ') |
||
Line 864: | Line 866: | ||
return rule |
return rule |
||
⚫ | |||
def makestring(rule, length): |
def makestring(rule, length): |
||
⚫ | |||
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]) |
|||
data = readdata(sys.argv[1]) |
|||
rule = makerule(data, int(sys.argv[2])) |
|||
string = makestring(rule, int(sys.argv[3])) |
|||
print(string)</lang> |
print(string)</lang> |
||
{{out}} |
{{out}} |