Python:从终端运行此代码

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (224)

我有这个代码,用于通过马尔可夫链/进程生成文本。它编译好没有错误,并在终端上运行没有错误,但不会产生任何响应/返回?

我这样做是通过进入目录来保存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 : ])
提问于
用户回答回答于

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

用户回答回答于

假设您的代码片段被正确复制,看起来您忘记了一定程度的缩进。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 : ])

扫码关注云+社区

领取腾讯云代金券