# 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)
```

つまり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.```