Last week, Matt the Suited Librarian challenged me to write a bit of code to automagically generate Shakespearean sonnets. Well, perhaps challenged is a bit strong — the idea came up in conversation, and I leapt at the idea. It’s been a while since I coded anything new.

First of all, I had to find a complete collection of Shakespeare’s sonnets, preferably in plain text. I ended up going with this collection from the Internet Archive. Next, I wrote a quick script to chop that longer file up into a collection of files, each one containing a single sonnet. In doing so, I discovered that Shakespeare wrote two sonnets that bend the rules slightly — one with one too many lines, and another that’s a line short. Still, when you’re The Bard you can afford to take a couple of literary liberties.

With my corpus collected, I started on the main generator. It randomly picks three sonnets, and then interweaves the lines from the first two picked, so that the lines of prose alternate between the two original sonnets. By only using two sonnets, the rhyming scheme is preserved, and the overall themes of the two still (sometimes) show through, meaning the results are not always complete garbage. The third randomly picked sonnet provides the closing rhyming couplet, so the endings do admittedly tend to be non sequiturs.

Here’s an example sonnet:

How careful was I when I took my way,
When that churl Death my bones with dust shall cover
That to my use it might unused stay
These poor rude lines of thy deceased lover,

But thou, to whom my jewels trifles are,
And though they be outstripp’d by every pen,
Thou best of dearest, and mine only care,
Exceeded by the height of happier men.

Thee have I not lock’d up in any chest,
‘Had my friend’s Muse grown with this growing age,
Within the gentle closure of my breast,
To march in ranks of better equipage:

Presume not on th’heart when mine is slain,
Thou gav’st me thine not to give back again..

It veers into gibberish, but you get the gist: aging and death and deceased lovers, all very Shakespearean woe-is-me. If you want to read some more (why?) the generator is online here, just reload the page for a new sonnet each time.

Shakespearean sonnets, remixed
Tagged on: