In an earlier article, I showed how we can generate poetry (with limitations, of course!) using my iLangGen framework. That implementation (in Lisp) made use of iLexicon, a large dictionary of English words, which I have been building over the years. I subsequently ported iLexicon to Prolog and it now works well in SICStus Prolog. In fact, I am quite pleased with its performance!
I decided to experiment with poetry generation using DCG (Definite Clause Grammars) in Prolog, simultaneously taking advantage of iLexicon to provide vocabulary for the generation task. Today’s article describes my approach.
The following code fragment sets up some English words for use in the generation.
As you can see (lines 22 – 27), I am pre-fetching some words from iLexicon and caching them for faster access during generation. This additionally facilitates randomizing the words.
The following shows the DCG rules for a simple grammar, capable of generating a single line of a poem. To add flexibility and variety, I have defined three “patterns” that can be used as templates for the generation.
The main clauses used to generate the poem are shown below.
I have defined two ways to generate a poem:
- Using a list of list of patterns, one list for each stanza
- Using a list of patterns and specifying the number of lines
Here are some outputs generated by the first variant:
The following outputs are based on the second variant:
As you might expect, the poem doesn’t make any sense, but I believe it is a good starting point. It is possible to make the generated poem more meaningful by introducing syntactic and semantic constraints. DCGs are quite elegant for such an experimentation. This is something I will be exploring in the future.
You may also want to take a look at a series of articles I wrote earlier about the support for DCGs in Lispworks Lisp.
Have a great weekend!
Recent Comments