Perl马尔科夫算法的小小改进

作者:半瓶墨水   链接:http://www.2maomao.com/blog/perl-markov-improvement/

本科的时候看过一本书《程序设计实践》,当时不是很懂马尔科夫算法是怎么一回事,被名词吓晕菜了。

近来又翻出这本书,把里面的Perl脚本实现的Markov程序敲进去,贴段圣经看了一下,发现结果很短且没有回车,稍微改进了一下程序:

#markov.pl: markov chain algorithm for 2-word prefixes
$MAXGEN = 10000;
$NONWORD = "\t";
$LINEFEED = "\n";
$w1 = $w2 = $NONWORD;               # initial state
while (<>) {                        # read each line of input
    
foreach (split) {
        
push(@{$statetab{$w1}{$w2}}, $_);
        
($w1, $w2) = ($w2, $_);     # mutiple assignment
    
}
    
push (@{$statetab{$w1}{$w2}}, $LINEFEED);
    
($w1, $w2) = ($w2, $LINEFEED)# mutiple assignment
}
push (@{$statetab{$w1}{$w2}}, $NONWORD);    # add tail
 
$w1 = $w2 = $NONWORD;
for ($i = 0; $i < $MAXGEN; $i++) {
    
$suf = $statetab{$w1}{$w2};     # array reference
    
$r = int(rand @$suf);           # @$suf is number of elems
    
exit if (($t = $suf->[$r]) eq $NONWORD);
    
print "$t ";
    
($w1, $w2) = ($w2, $t);         #advance chain
}

下面是一段由圣经Kings1(列王记上)部分做源输入生成的结果:

The young lady was very fair; and she is to the king. <---(兔毛猫评论:这句比较搞笑:) And Zadok the priest, and Nathan the prophet also came in. While you are still speaking with the king, Nathan the prophet;' and he also of a very goodly man; and he shall reign after me, and he aros e, and went, and caught hold of the kingdom. And the king into the chamber: and the Pel'ethites; and they have caused him to be king after him; And Zadok the priest, and Nathan the prophet;' and he shall sit upon my throne; for he shall sit on my seat in my stead: and I have appoint ed him to Gihon. So they sought for my lord king David, saying, God make the name of Solomon better than thy name, and his servants said unto them, Take wit h you the trumpet, he said, "What do you behave as you do?" He was also a very comely man; and bore him after Absalom. and he shall die. And it was told Solomon saying, Behold, Adonijah feareth because of Solomon, and arose and went away, every man his way. And Jonathan, answering, said to him, Go to thy handmaid saying, Solomon thy son shall reign after me, and he invited all the king's mule;

注意运行perl markov.pl的时候,输入的内容以Ctrl+Z然后回车做结束,不是空行。

留下回复