Categories
Uncategorized

Substituting words with lists and dictionaries – Python

So we have the following string

'Brighton is terrible. Full of disgusting beer, and ugly women.'

Except that it does not paint a good picture of Brighton, and The Man doesn’t like it.

There are two things that we can do. We can substitute all the negative words with the same item using a list, or we can swap the negative words with nicer ones using a dictionary.

Using a list

Using a list we can sensor all the negative words by replacing them with ‘#####’

We first create a list of all the words The Man doesn’t agree with

list_negative_words = ['terrible','disgusting','ugly']

Now we can use re.sub()


from re import sub

str_bad_string = 'Brighton is terrible. Full of disgusting beer, and ugly women.'

list_negative_words = ['terrible','disgusting','ugly']

str_censored_string = sub('|'.join(list_negative_words),
							'#######',
							str_bad_string)
print str_censored_string

That should return

'Brighton is #######. Full of ####### beer, and ####### women.'

Not bad…but not great either.

Using a Dictionary

Using a dictionary we can replace each negative word with something nice – like ‘terrible’ with ‘awesome’, ‘disgusting’ with ‘amazing’, and ‘ugly’ with ‘beautiful’.

First we create the dictionary

dict_the_mans_dictionary = {'terrible':'awesome',
							'disgusting':'amazing',
							'ugly':'beautiful'}

then we run it through a loop


str_bad_string = 'Brighton is terrible. Full of disgusting beer, and ugly women.'

for str_each_item in dict_the_mans_dictionary:
	str_bad_string = sub(str_each_item,
						dict_the_mans_dictionary[str_each_item],
						str_bad_string)

print str_bad_string

and that returns

'Brighton is awesome. Full of amazing beer, and beautiful women.'

There!
Brighton’s reputation is preserved.

Leave a Reply

Please log in using one of these methods to post your comment:

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