Skip to content Skip to sidebar Skip to footer

Python Regex: Find Words And Emoticons

I want to find matches between a tweet and a list of strings containing words, phrases, and emoticons. Here is my code: words = [':)','and i','sleeping','... :)','! <3','faceboo

Solution 1:

I tried the below and it stopped throwing the error:

words = [':\)','and i','sleeping','... :\)','! <3','facebook']

Solution 2:

The re module has a function escape that takes care of correct escaping of words, so you could just use

words = map(re.escape, [':)','and i','sleeping','... :)','! <3','facebook'])

Note that word boundaries might not work as you expect when used with words that don't start or end with actual word characters.


Solution 3:

While words has all the necessary formatting, re uses ( and ) as special characters. This requires you to use \( or \) to avoid them being interpreted as special characters, but rather as the ASCII characters 40 and 41. Since you didn't understand what @Nicarus was saying, you need to use this:

words = [':\)','and i','sleeping','... :\)','! <3','facebook']

Note: I'm only spelling it out because this doesn't seem like a school assignment, for all the people who might want to criticize this. Also, look at the documentation prior to going to stack overflow. This explains everything.


Post a Comment for "Python Regex: Find Words And Emoticons"