Python:从终端运行此代码

时间:2018-07-14 12:12:00

标签: python markov-chains markov

我有这段代码,旨在通过马尔可夫链/流程生成文本。它编译良好,没有错误,并且可以在终端上运行且没有错误,但是不会生成任何响应/返回?

我通过进入保存Markov.py文件的目录并在终端上运行Python3 Markov.py来执行此操作,如下所示 enter image description here

我知道我做错了什么,但不确定是什么,我还需要调用函数吗?

import random

class Markov (object):
    def __init__(self,order):
        self.order = order
        self.group_size = self.order + 1 
        self.text = "testFile.txt"  #The training text
        self.graph = {}  #Holds the information learnt
        return

    def train (self,filename):
        self.text = file (testFile.txt).read () .split()    
        self.text = self.text + self.text [ : self.order]   
        for i in range (0, len (self.text) - self.group_size):
            key = tuple (self.text [i : i + self.order]) 
            value = self.text[i + self.order] 

            if key in self.graph:
                self.graph [key].append (value)
            else:
                self.graph [key] = [value]

    def generate (self, length):
        index = random.randint (0, len(self.text) - self.order)
        result = self.text[index : index + self.order]
        for i in range (length):
            state = tuple(result[len(result) - self.order:])
            next_word = random.choice(self.graph[state])
            result.append(next_word)

        return " ".join (result[self.order : ])

x = Markov(2)
files = open("testFile.txt", "r")
filename = files

x.train(filename)
print(x.generate(10))

2 个答案:

答案 0 :(得分:3)

假设您的代码段已正确复制,则好像您忘记了缩进级别。 generate()和train()方法是Markov()对象的一部分,因此它们需要额外的缩进级别。

尝试一下:

import random

class Markov (object):
    def __init__(self,order):
        self.order = order
        self.group_size = self.order + 1 
        self.text = "testFile.txt"  #The training text
        self.graph = {}  #Holds the information learnt
        return

    def train (self,filename):
        self.text = file (testFile.txt).read () .split()    
        self.text = self.text + self.text [ : self.order]   
        for i in range (0, len (self.text) - self.group_size):
            key = tuple (self.text [i : i + self.order]) 
            value = self.text[i + self.order] 

            if key in self.graph:
                self.graph [key].append (value)
            else:
                self.graph [key] = [value]

    def generate (self, length):
        index = random.randint (0, len(self.text) - self.order)
        result = self.text[index : index + self.order]
        for i in range (length):
            state = tuple(result[len(result) - self.order:])
            next_word = random.choice(self.graph[state])
            result.append(next_word)

        return " ".join (result[self.order : ])

答案 1 :(得分:1)

是的,您必须在代码中调用这些函数,否则它们将不会被调用也不会运行。您只需调用一个类,就必须实例化该类,尝试实例化您的类并适当地调用函数。 有关功能的更多信息,请参见here