forked from capnrefsmmat/seuss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmakeChains.py
53 lines (43 loc) · 1.56 KB
/
makeChains.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/python
"""
Generate Markov chains to be cached in the filesystem; this saves us the effort
of generating new chains every time we want to make poetry.
"""
import sys, Markov, glob, os
def makeChain(name, sourceDir, cacheDir):
"""Parse the source text to generate new Markov chains."""
sourceFile = sourceDir + name + ".txt"
fwd = Markov.MarkovChain(cacheDir + name + "-fwd", 1, True)
rev = Markov.MarkovChain(cacheDir + name + "-rev", 1, True)
try:
for line in open(sourceFile):
words = line.split()
if len(words) > 0:
fwd.add(words)
words.reverse()
rev.add(words)
except IOError:
print "The source named '%s' does not exist" % (name,)
finally:
fwd.close()
rev.close()
def deleteChainCache(name, cacheDir):
"""Delete the old cached versions of the chains, so we start fresh rather
than adding to the previous chain files."""
try:
os.remove(cacheDir + name + "-fwd")
os.remove(cacheDir + name + "-rev")
except OSError:
# if they don't exist, we don't care
pass
if __name__ == "__main__":
if len(sys.argv) < 2:
print """Usage:
makeChains.py chainName
where chainName is a specific source text to parse and cache."""
sys.exit(1)
print "Deleting old cache files"
deleteChainCache(sys.argv[1], "cache/")
print "Creating new cache files"
makeChain(sys.argv[1], "sources/", "cache/")
print "Chain(s) created successfully."