简体   繁体   中英

Program error in text prediction algorithm in Python 2.7

I came across the following code from this question :

from collections import defaultdict
import random

class Markov:
    memory = defaultdict(list)
    separator = ' '

    def learn(self, txt):
        for part in self.breakText(txt):
            key = part[0]
            value = part[1]

            self.memory[key].append(value)

    def ask(self, seed):
        ret = []

        if not seed:
            seed = self.getInitial()

        while True:
            link = self.step(seed)

            if link is None:
                break

            ret.append(link[0])
            seed = link[1]

        return self.separator.join(ret)

    def breakText(self, txt):
        #our very own (ε,ε)
        prev = self.getInitial()

        for word in txt.split(self.separator):
            yield prev, word
            prev = (prev[1], word)

        #end-of-sentence, prev->ε
        yield (prev, '')

    def step(self, state):
        choice = random.choice(self.memory[state] or [''])

        if not choice:
            return None

        nextState = (state[1], choice)
        return choice, nextState

    def getInitial(self):
        return ('', '')

When i ran the code on my system the example didn't work.

When i ran the bob.ask() line i got an error saying ask() required 2 parameters whereas it got just one. Also when i ran the bob.ask("Mary had") part i got ' ' as the output.

PS I ran the the code exactly as told in the answer.

Could anyone help? Thanks!

I think you're right. It doesn't work because ask expects an argument ( seed ), as defined by

def ask(self, seed): 

This line

if not seed:
    seed = self.getInitial()

suggests that you can fix the issue by setting a default argument for seed . Try this:

def ask(self, seed=False):

which works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM