In this paper, the method of implementing the Markov chain algorithm in Python is described. Share to everyone for your reference. The specific analysis is as follows:
In the book "The Practice of Programming" (English name "The Practice of Programming"), the third chapter, respectively, uses the C language, C++,awk and Perl respectively to implement the horse-ear-chain algorithm to generate some useful text through the input of the text, "random".
Description
1. The program uses a dictionary, dictionary and Hash is not a thing, the dictionary is a set of key-value pairs, and hashing is a constant order to insert, delete, but you can use hash to implement the dictionary.
2. The SetDefault () method of the dictionary makes the procedure much less conditional judgment.
3. Random.choice () can randomly remove elements from a sequence.
4. Each of the two prefix words determines a suffix.
Implementation code:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22 |
Import random Import sys Maxgen = 10000 Nonword = ' n ' w1 = W2 = Nonword Statetab = {} text = Sys.stdin.read () words = text . Split () for Word in Words:statetab.setdefault (W1, W2), []). Append (Word) w1, W2 = W2, Word # Add tail statetab.setdefault ((W1, W2), []). Append (Nonword) # show Mar words w1 = W2 = Nonword to I in Xrange (maxgen): Suf = statetab[(w1,w2)] t = Rand Om.choice (SUF) If t = = nonword:break print t w1, w2 = W2, T |
I hope this article will help you with your Python programming.