Generating Poetry in Prolog

Written by on August 4, 2019 in Natural Language Processing, Programming, Prolog with 0 Comments

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.

Setting up the Vocabulary

Setting up the Vocabulary

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.

DCG Rules

DCG Rules

The main clauses used to generate the poem are shown below.

Generation Logic

Generation Logic

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:

Sample Output 1

Sample Output 1

 

Sample Output 2

Sample Output 2

 

The following outputs are based on the second variant:

Sample Output 3

Sample Output 3

 

Sample Output 4

Sample Output 4

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!

Tags: , , ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top