gpt4 book ai didi

python - 'MarkovGenerator' 对象没有属性 'together'

转载 作者:太空宇宙 更新时间:2023-11-04 09:09:58 26 4
gpt4 key购买 nike

我想出了一个关于类(class)的问题,我不知道原因,有没有人能帮我解决?

问题出在 def together() 中,这是我的代码。

class MarkovGenerator(object):

def __init__(self, n, max):
self.n = n # order (length) of ngrams
self.max = max # maximum number of elements to generate
self.ngrams = dict() # ngrams as keys; next elements as values
beginning = tuple(["That", "is"]) # beginning ngram of every line
beginning2 = tuple(["on", "the"])
self.beginnings = list()
self.beginnings.append(beginning)
self.beginnings.append(beginning2)
self.sentences = list()


def tokenize(self, text):
return text.split(" ")

def feed(self, text):

tokens = self.tokenize(text)

# discard this line if it's too short
if len(tokens) < self.n:
return

# store the first ngram of this line
#beginning = tuple(tokens[:self.n])
#self.beginnings.append(beginning)

for i in range(len(tokens) - self.n):

gram = tuple(tokens[i:i+self.n])
next = tokens[i+self.n] # get the element after the gram

# if we've already seen this ngram, append; otherwise, set the
# value for this key as a new list
if gram in self.ngrams:
self.ngrams[gram].append(next)
else:
self.ngrams[gram] = [next]

# called from generate() to join together generated elements
def concatenate(self, source):
return " ".join(source)

# generate a text from the information in self.ngrams
def generate(self,i):

from random import choice

# get a random line beginning; convert to a list.
#current = choice(self.beginnings)
current = self.beginnings[i]
output = list(current)

for i in range(self.max):
if current in self.ngrams:
possible_next = self.ngrams[current]
next = choice(possible_next)
output.append(next)
# get the last N entries of the output; we'll use this to look up
# an ngram in the next iteration of the loop
current = tuple(output[-self.n:])
else:
break

output_str = self.concatenate(output)
return output_str


def together(self):
return "lalala"


if __name__ == '__main__':

import sys
import random


generator = MarkovGenerator(n=2, max=16)
for line in open("us"):
line = line.strip()
generator.feed(line)

for i in range(2):
print generator.generate(i)
print generator.together()

但我收到错误消息:

Traceback (most recent call last):
File "markovoo2.py", line 112, in <module>
print generator.together()
AttributeError: 'MarkovGenerator' object has no attribute 'together'

有谁知道原因吗?

最佳答案

您将 def together() 函数定义缩进太多,它是 def generate() 函数体的一部分。

取消缩进以匹配类主体中的其他函数。

关于python - 'MarkovGenerator' 对象没有属性 'together',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com