WordPress – Trash offensive comments with Python

New WordPress users (like me) may want to block comments that contain any nasty words which may be used by those less able to express themselves in the English language than the average slug.

I noticed that in ‘Settings’ –> ‘Discussions’ there is an option to trash comments that contain certain words under ‘Comment Blacklist’. This says you should enter one word or IP per line. So being lazy, I searched for a list of ‘bad’ words to copy and paste. I found one at:


Please note that this file contains words and phrases that are particularly offensive and should not be viewed by the fainthearted. I view them as words that should be immediately trashed by any blogger as a matter of course and would advise anyone to do the same.

Unfortunately it is a comma separated list of words. I need each bad word on a single line to easily copy and paste. The original file is:
‘bad word,bad word,bad word…..
but I want a list of words line by line.
bad word
bad word
bad word …..
Python easily manipulates text to your desired format. In this case I wanted to strip out the commas and replace them with a new line. That is string.replace(‘,’,’\n’)

Simples! Here is the code in Python3:

The main point to notice in the code is the use of ‘with open’. It automatically closes the file for you. Bear in mind that this is not a performance gain or indeed loss. It is just tidier IMHO.

This is quick and dirty but if we want something a bit more sophisticated we might define a function to do the work for us regardless of the file names being hard wired. Why not try something like:

We have now defined a function that does exactly the same thing as the original code but now accepts user choices for the input and output file names.

There is more to be done for error checking..making sure that we are in the correct path using sys and using try to catch errors, but you will just have to wait for next weeks exciting episode. Click to download a PDF version of the code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s