This article mainly introduces how to implement the Markov chain algorithm in python. The example analyzes the principles and implementation skills of the Markov chain algorithm, for more information, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
In The program design Practice (The Practice of Programming), Chapter 3 uses C language, C ++, AWK, and Perl to implement The Markov chain algorithm, to generate some useful text randomly based on the input text.
Note:
1. the program uses a dictionary. the dictionary and hash are not a set of key-value pairs, while the hash is a constant-order insertion and deletion function, however, you can use hash to implement the dictionary.
2. the setdefault () method of the dictionary makes the program less conditional judgment.
3. random. choice () can randomly retrieve elements in a sequence.
4. determine a suffix for each two prefix words.
Implementation code:
Import randomimport sysMAXGEN = 10000 NONWORD = '\ n' w1 = w2 = NONWORDstatetab = {} text = sys. stdin. read () words = text. split () for word in words: statetab. setdefault (w1, w2), []). append (word) w1, w2 = w2, word # add tailstatetab. setdefault (w1, w2), []). append (NONWORD) # show mar wordsw1 = w2 = NONWORDfor I in xrange (MAXGEN): suf = statetab [(w1, w2)] t = random. choice (suf) if t = NONWORD: break print t w1, w2 = w2, t
I hope this article will help you with Python programming.