이들 변수는 전역이므로 한 번에 분석 하나만 실행할 수 있다. 텍스트 두 개를 읽어 들이면 두 텍스트의 접두어와 접미어가 같은 자료 구조에 추가되어 버린다(이렇게 해서 생성된 텍스트가 흥미로울 수는 있다).
분석을 여러 개 실행하고 이를 분리된 상태로 유지하려면 각 분석의 상태를 객체로 캡슐화해야 한다. 즉, 다음과 같이 코드를 작성해야 한다.
class Markov:
def _ _init_ _(self):
self.suffix_map = {}
self.prefix = ()
다음은 함수를 메서드로 변환하는 것이다. 예를 들어 process_word를 다음과 같이 변환한다.
def process_word(self, word, order=2):
if len(self.prefix) < order:
self.prefix += (word,)
return
try:
self.suffix_map[self.prefix].append(word)
except KeyError:
# 이 접두어에 대한 항목이 없다면 항목을 만든다
self.suffix_map[self.prefix] = [word]
self.prefix = shift(self.prefix, word)