Convert text to Pirate Talk in Python

AAARRR! Pirate talk is a varient of English inspired by 16th centuary pirates and used in Talk like a pirate day, and Facebook's English (Pirate) language option.

There's an open source programme, pirate that converts text to pirate speak, it's part of the filters package (ubuntu install link). It reads english on the stdin and prints the pirate speak on the stdout.

It's quite easy to run an external programme in Python using the subprocess module. It has several convenience functions for just running a process and getting the return code (check_call) or getting the output (check_output). However they don't interact with the programme at all, and the pirate command line tool reads off stdin, not the arguments.

Python function

Here's a python function that will take an input english string and return how a pirate would say it.

import subprocess def translate(english): translater = subprocess.Popen('pirate', stdin=subprocess.PIPE, stdout=subprocess.PIPE) translater.stdin.write(english.encode("utf8")+"\n") piratese, _ = translater.communicate() # chop off the trailing new line piratese = piratese[:-1] return piratese

Adding custom translations

You may want to add some extra translations specific for you domains (e.g. I made it translate 'Log out' as 'Abandon Ship'). You can do this by adding english = english.replace("Log out", "Abandon Ship") at the start of the function

This entry is tagged: