プログラミング演習として、単語の連鎖に対して任意の長さのマルコフジェネレーターを作成しようとしていますが、修正できないバグを見つけました。マルコフ関数を実行すると、リストインデックスが範囲外になります。
当たり前のことを見落としているような気がしますが、何なのかわかりません。トレースバックは、エラーが41行目にあることを示していwords[-1] = nextWords[random.randint(0, len(nextWords)-1)]
ます。
完全なコードは以下のとおりです。インデントが台無しになっている場合は申し訳ありません。
#! /usr/bin/python
# To change this template, choose Tools | Templates
# and open the template in the editor.
import random
class Markov(object):
def __init__(self, open_file):
self.cache = {}
self.open_file = open_file
open_file.seek(0)
self.wordlist = open_file.read().split()
def get_random_list(self, length):
i = random.randint(0, len(self.wordlist) - (length - 1))
result = self.wordlist[i:i + length]
return result
def find_next_word(self, words):
candidates = []
for i in range(len(self.wordlist) - len(words)):
if self.wordlist[i:i + len(words)] == words and self.wordlist[i+len(words)+1] not in candidates:
candidates.append(self.wordlist[i+len(words)+1])
return candidates
def markov(self, length=20, chainlength=2):
gibberish = []
words = self.get_random_list(chainlength)
for i in range(len(words)-1):
gibberish.append(words[i])
while len(gibberish) < length:
#find candidate for next word
nextWords = self.find_next_word(words)
gibberish.append(words[-1])
for i in range(len(words)):
try:
words[i] = words[i+1]
except:
pass
words[-1] = nextWords[random.randint(0, len(nextWords)-1)]
return " ".join(gibberish)