4 def __init__(self
, histsize
, choice
):
5 self
.histsize
= histsize
8 def add(self
, state
, next
):
9 if not self
.trans
.has_key(state
):
10 self
.trans
[state
] = [next
]
12 self
.trans
[state
].append(next
)
17 for i
in range(len(seq
)):
18 add(seq
[max(0, i
-n
):i
], seq
[i
:i
+1])
19 add(seq
[len(seq
)-n
:], None)
24 seq
= choice(trans
[None])
26 subseq
= seq
[max(0, len(seq
)-n
):]
27 options
= trans
[subseq
]
28 next
= choice(options
)
34 import sys
, string
, random
, getopt
37 opts
, args
= getopt
.getopt(args
, '0123456789cdw')
39 print 'Usage: markov [-#] [-cddqw] [file] ...'
41 print '-#: 1-digit history size (default 2)'
42 print '-c: characters (default)'
44 print '-d: more debugging output'
45 print '-q: no debugging output'
46 print 'Input files (default stdin) are split in paragraphs'
47 print 'separated blank lines and each paragraph is split'
48 print 'in words by whitespace, then reconcatenated with'
49 print 'exactly one space separating words.'
50 print 'Output consists of paragraphs separated by blank'
51 print 'lines, where lines are no longer than 72 characters.'
56 if '-0' <= o
<= '-9': histsize
= eval(o
[1:])
57 if o
== '-c': do_words
= 0
58 if o
== '-d': debug
= debug
+ 1
59 if o
== '-q': debug
= 0
60 if o
== '-w': do_words
= 1
61 if not args
: args
= ['-']
62 m
= Markov(histsize
, random
.choice
)
68 print 'Sorry, need stdin from file'
71 f
= open(filename
, 'r')
72 if debug
: print 'processing', filename
, '...'
75 paralist
= string
.splitfields(text
, '\n\n')
77 if debug
> 1: print 'feeding ...'
78 words
= string
.split(para
)
80 if do_words
: data
= tuple(words
)
81 else: data
= string
.joinfields(words
, ' ')
83 except KeyboardInterrupt:
84 print 'Interrupted -- continue with data read so far'
86 print 'No valid input files'
88 if debug
: print 'done.'
90 for key
in m
.trans
.keys():
91 if key
is None or len(key
) < histsize
:
92 print repr(key
), m
.trans
[key
]
93 if histsize
== 0: print repr(''), m
.trans
['']
97 if do_words
: words
= data
98 else: words
= string
.split(data
)
102 if n
+ len(w
) > limit
:
111 if len(list) == 0: return ()
112 if len(list) == 1: return (list[0],)
114 return tuple(list[:i
]) + tuple(list[i
:])
116 if __name__
== "__main__":