-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword-game.py
73 lines (59 loc) · 1.86 KB
/
word-game.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from markov import markov
import cPickle
import sys
depth = 5
punc = [ '.', '?', '!' ]
def clean( word ):
bad_chars = []
for letter in word.lower():
if (letter > 'z' or letter < 'a') and letter not in punc:
bad_chars.append( letter )
for char in bad_chars:
word = word.replace( char, '' )
return word.lower()
def load( filename ):
Markov = markov()
Markov = cPickle.load( open( ".m_" + filename + '.dmp', "rb" ) )
return Markov
def save( filename, Markov ):
cPickle.dump( Markov, open( '.m_' + filename + '.save.dmp', "wb" ) )
def play( filename, Markov ):
Words = [ '' ]
while( True ):
if len( Words ) > depth:
Words.pop(0)
next_word = None
i = min( [depth, len( Words )] )
while next_word == None and i > 0:
next_word = Markov.predict( ' '.join(Words[ -i:]).lower() )
i -= 1
if next_word == None:
next_word = Markov.predict( '' )
Words.append( next_word )
sys.stdout.write( '%s ' % next_word )
sys.stdout.flush()
for word in raw_input().split(' '):
if word == '': break
next_word = clean( word )
if next_word == '!!!!!':
save( filename, Markov )
return
i = min( [depth, len( Words )] )
while next_word == None and i > 0:
next_word = Markov.record( ' '.join(Words[ -i:]).lower(), next_word )
i -= 1
Words.append( next_word )
def main():
if len( sys.argv ) < 2:
print 'Not enough args'
return
try:
f = open( '.m_' + sys.argv[1] + '.dmp' )
f.close()
except IOError as e:
print 'No file data exists...'
return
Markov = load( sys.argv[1] )
play( sys.argv[1], Markov )
if __name__ == '__main__':
main()