2015-10-29 69 views
2

我想寫一個代碼,可以創建幾個句子,也是用戶請求的單詞,但我遇到了一些問題,找不到答案全能谷歌。尋找任何建議(另外,我認爲有一種方法可以縮短)。使用生成器來從給定的單詞製作句子

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 
+0

作爲一個說明,該巨型'if' /'elif'塊可以通過使用可變 - 代替'下(self.generators [W])' - 或者如果您需要驗證內容,請事先檢查該值是否在一個集合中。 I.e:'如果w in {'名詞,'目標,'動詞',...}:next(self.generators [w])'。 –

+1

你可以用'名詞'來替換所有這些''名詞':self.generator(self.nouns),'iter(self.nouns),'。另外,它似乎像'create_sentence'應該返回一些東西,但它不。你的意思是「接下來的(...)」嗎? –

+0

由於簡單的印刷錯誤,我正在關閉標記。 'str.split'上的答案缺少parens'()'。 (請參閱@Latty的回答) –

回答

1

你是不是叫str.split(),而是你正試圖遍歷功能(不是結果調用的說功能)。

for w in syntax.split: 
    ... 

應該是:

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

哦,那是一個愚蠢的錯誤..認爲它會更困難。謝謝。 – Kert