Example #1
0
    def walk(self, num_sentences=10):
        # Get random starting point from keys
        starting_points = list(filter(lambda x: x[0] is None, self.keys()))
        chain = list(random.choice(starting_points))
        queue = LinkedQueue(chain)

        sentences = 0
        while sentences < num_sentences:
            prev_words = tuple(queue.items())
            new_word = self[prev_words].sample()

            queue.enqueue(new_word)
            queue.dequeue()

            if new_word is None:
                sentences += 1
            else:
                chain.append(new_word)

        phrase = []
        for segment in chain[1:]:
            # Word
            if re.match(r'\w+', segment) is None:
                phrase[-1] += segment
            else:
                phrase.append(segment)

        result = ' '.join(phrase)
        return result