Skip to main content
 首页 » 编程设计

python之使用生成器从给定的单词造句

2025年05月04日15thcjp

我正在尝试编写一个代码来创建一些句子以及用户请求的单词,但我遇到了一些问题,无法从全能的 Google 中找到答案。寻找任何建议(另外,我认为有一种方法可以缩短它)。

class CallCentre(object): 
 
    """This is a class.""" 
 
    def __init__(self): 
        self.nouns = ['koer', 'porgand', 'madis', 'kurk', 'tomat'] 
        self.targets = ['koera', 'porgandit', 'madist', 'kurki', 'tomatit'] 
        self.verbs = ['sööb', 'lööb', 'jagab', 'tahab', 'ei taha'] 
        self.adjectives = ['ilus', 'kole', 'pahane', 'magus', 'sinu'] 
        self.targetadjectives = ['ilusat', 'koledat', 'pahast', 'magusat', 'sinu'] 
        self.sentence = 'noun verb target' 
        self.twosentences = 'sentence sentence' 
        self.beautifulsentence = 'adjective noun verb targetadjective target .' 
 
        self.generators = { 
            'noun': self.generator(self.nouns), 
            'target': self.generator(self.targets), 
            'verb': self.generator(self.verbs), 
            'adjective': self.generator(self.adjectives), 
            'targetadjective': self.generator(self.targetadjectives), 
            'sentence': self.generator(self.sentence), 
            'twosentences': self.generator(self.twosentences), 
            'beautifulsentence': self.generator(self.beautifulsentence) 
        } 
 
    def generator(self, array): 
        i = -1 
        while True: 
            i = (i + 1) % 5 
            yield array[i] 
 
    def create_sentence(self, syntax): 
        for w in syntax.split: 
            if w == 'noun': 
                next(self.generators['noun']) 
            elif w == 'target': 
                next(self.generators['target']) 
            elif w == 'verb': 
                next(self.generators['verb']) 
            elif w == 'adjective': 
                next(self.generators['adjective']) 
            elif w == 'targetadjective': 
                next(self.generators['targetadjective']) 
            elif w == 'sentence': 
                next(self.generators['sentence']) 
            elif w == 'twosentences': 
                next(self.generators['twosentences']) 
            elif w == 'beautifulsentence': 
                next(self.generators['beautifulsentence']) 
 
if __name__ == '__main__': 
    centre = CallCentre() 
    print(centre.create_sentence('noun')) 

这是错误信息:

  Traceback (most recent call last): 
  File "this file", line 56, in <module> 
    print(centre.create_sentence('noun')) 
  File "this file", line 36, in create_sentence 
    for w in syntax.split: 
TypeError: 'builtin_function_or_method' object is not iterable 
 
Process finished with exit code 1 

请您参考如下方法:

您不是在调用 str.split(),而是在尝试迭代函数(不是调用所述函数的结果)。

for w in syntax.split: 
    ... 

应该是:

for w in syntax.split(): 
    ...