@@ -0,0 +1,2002 @@
+#!/usr/bin/env python%0A# encoding: utf-8%0A# Script that generates three random sentences from the%0A# hard-code grammar. In general, the grammar would be%0A# stored in a data file, but to be honest, it would likely%0A# be encoded as a serialized dictionary, since that would make it%0A# trivial to deserialize the data.%0A%0Aimport sys%0Afrom random import seed, choice%0A%0Agrammar = %7B '%3Cstart%3E': %5B%5B'The ', '%3Cobject%3E', ' ', '%3Cverb%3E', ' tonight.'%5D%5D,%0A%09%09    '%3Cobject%3E': %5B%5B'waves'%5D, %5B'big yellow flowers'%5D, %5B'slugs'%5D%5D,%0A%09%09    '%3Cverb%3E': %5B%5B'sigh ', '%3Cadverb%3E'%5D, %5B'portend like ', '%3Cobject%3E'%5D%5D,%0A%09%09    '%3Cadverb%3E': %5B%5B'warily'%5D, %5B'grumpily'%5D%5D %7D%0A%0A%0A# Expands the specified symbol into a string of terminals. If the symbol is already a terminal,%0A# then we just print it as is to sys.stdout. Otherwise,%0A# we look the symbol up in the grammar, choose a random expansion, and map the expand function over it.%0A# Note the mapping functionality that comes with map. Scheme has its influences, people!%0A%0Adef expand(symbol):%0A%09if symbol.startswith('%3C'):%0A%09%09options = grammar%5Bsymbol%5D%0A%09%09production = choice(options)%0A%09%09# print('production=',production, %22 islist:%22, isinstance(production,list))%0A%09%09list(map(expand, production)) #should add list() for Python 3.3, using 3.1's map would be lazy evaluation when iterating on a complex function, large data sets, or streams%0A%09else:%0A%09%09sys.stdout.write(symbol)%0A%09%09# print(%22www%22)%0A%0A# Seeds the randomization engine, and the procceds to generate three random sentences.%0A# We use sys.stdout so we have a little more control over formatting.%0A%0Adef generateRandomSentences(numSentences):%0A%09seed()%0A%09for iteration in range(numSentences):%0A%09%09sys.stdout.write(str(iteration + 1))%0A%09%09sys.stdout.write('.) ')%0A%09%09expand('%3Cstart%3E')%0A%09%09sys.stdout.write('%5Cn')%0A%0Adef printfunc(sth):%0A%09print('88:',sth)%0A%0AgenerateRandomSentences(3)%0A# list(map(printfunc, %5B'The ', '%3Cobject%3E', ' ', '%3Cverb%3E', ' tonight.'%5D))%0A# map(printfunc, %5B'The ', '%3Cobject%3E', ' ', '%3Cverb%3E', ' tonight.'%5D)%0Aprint(list(map(chr,%5B66,53,0,94%5D)))%0Aprint(map(chr,%5B66,53,0,94%5D))%0A

check in RSG