Python: 运行 来自终端的代码

Python: Running this code from terminal

我有这段代码,旨在通过马尔可夫 chains/processes 生成文本。它编译正常,没有错误,在终端上运行也没有错误,但不生成任何 response/return?

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

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

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

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

假设您的代码片段已正确复制,您似乎忘记了缩进级别。 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 : ])