Kodomo

Пользователь

Пример решения

   1 import random
   2 
   3 nouns = ["dog", "fox", "ball", "boy", "tree", "song"]
   4 t_verbs = ["eat", "catch", "sing"]
   5 nt_verbs = ["run", "jump"]
   6 adjectives = ["dirty", "clean", "ugly", "beatuful", "brown", "quick", "lazy", "eager"]
   7 prepositions = ["in", "over", "about"]
   8 
   9 avg_n_adjectives = 0.8
  10 plural_prob = 0.5
  11 preposition_prob = 0.5
  12 object_prob = 0.5
  13 
  14 class Phrase(object):
  15         def text(self):
  16                 return " ".join(self.repr())
  17 
  18 class NP(Phrase):
  19         def __init__(self, preposition_prob = preposition_prob):
  20                 n_adjectives = int(random.expovariate(1 / avg_n_adjectives))
  21                 self.adjectives = random.sample(adjectives, n_adjectives)
  22                 self.noun = random.choice(nouns)
  23                 self.prepositions = []
  24                 self.plural = random.random() < plural_prob
  25                 if random.random() < preposition_prob:
  26                         self.prepositions.append(random.choice(prepositions))
  27         def repr(self):
  28                 if self.plural:
  29                         self.noun += "s"
  30                 return self.prepositions + self.adjectives + [self.noun]
  31 
  32 class VP(Phrase):
  33         def __init__(self):
  34                 self.verb = random.choice(t_verbs + nt_verbs)
  35                 self.object = None
  36                 if self.verb in t_verbs:
  37                         self.object = NP()
  38                         self.object.prepositions = []
  39                 elif random.random() < object_prob:
  40                         self.object = NP(1)
  41         def repr(self, plural):
  42                 if not plural:
  43                         self.verb += "s"
  44                 words = [self.verb]
  45                 if self.object:
  46                         words += self.object.repr()
  47                 return words
  48 
  49 class Sentence(Phrase):
  50         def __init__(self):
  51                 self.np = NP()
  52                 self.np.prepositions = []
  53                 self.vp = VP()
  54         def repr(self):
  55                 words = self.np.repr() + self.vp.repr(self.np.plural)
  56                 words[0] = words[0].capitalize()
  57                 return words
  58 
  59 if __name__ == "__main__":
  60         sentence = Sentence()
  61         print sentence.text() + "."