msmazh msmazh - 23 days ago 7
Python Question

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','facebook']
regex = re.compile(r'\b%s\b|(:\(|:\))+' % '\\b|\\b'.join(words), flags=re.IGNORECASE)


I keep receiving this error:

error: unbalanced parenthesis


Apparently there is something wrong with the code and it cannot match emoticons. Any idea how to fix it?

Answer

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.