何かを書き留める何か

数学や読んだ本について書く何かです。最近は社会人として生き残りの術を学ぶ日々です。

Markov連鎖アルゴリズムによるデタラメ英文

プログラミング作法

プログラミング作法


"プログラム作法"の第3章ではランダムな英文を作成するプログラムを題材にプログラムの設計と実装の方法が書いてある。面白そうだったのでPythonで実装してみることにした。なお本文中にはC, Java, C++, Awk, Perlで実装してある。
面白そうと思った理由は、設計を考えるときにデータ構造で使ったことが無かったディクショナリを使う練習として面白そうに思えたからである。


# -*- coding: UTF-8 -*-

import random
import sys

word_list = []
markov_dict = {}
input_file = open(sys.argv[1],"r")
for line in input_file:
    word_list += line.rstrip("\n").split(" ")

for x in range(len(word_list)):
    try:
        tmp = word_list[x]+ " " +word_list[x+1]
        if tmp in markov_dict:
            markov_dict[tmp].append(word_list[x+2])
        else:
            markov_dict[tmp] = [word_list[x+2]]
        del tmp
    except IndexError:
        pass
    
output_word = random.choice([x for x in markov_dict.keys()
                             if x[0].isupper()]).split(" ")

tmp = random.choice(markov_dict[output_word[-2] + " " + output_word[-1]])
while (len(output_word) < 100):
    try:
        output_word.append(tmp)
        tmp = random.choice(
            markov_dict[output_word[-2] + " " + output_word[-1]])
        if tmp == "EOF":
            break
    except (IndexError, TypeError, KeyError):
        pass

out = "".join([x + " " for x in output_word])
print(out)

出力例は以下の通り。なお題材のテキストはhttp://www.gutenberg.org/ebooks/11から引用した。
つまりLewis Carroll のような文章を出力する。

THAT!'  'Oh, don't talk about cats or dogs either, if you were or might have been
 changed in the shade: however, the moment he was gone, and the White Rabbit 
cried out, 'Silence in the air, I'm afraid, but you might like to have lessons to
learn! No, I've made up my mind about it; if I'm Mabel, I'll stay down here! 
It'll be no chance of this, so she took courage, and went on eagerly.  
'That's nothing to what I was going to do anything but sit with its arms folded, 
frowning like a star-fish,' thought Alice.