Python regex: find words and emoticons

梦想的初衷 提交于 2020-01-07 08:07:23

问题


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?


回答1:


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.




回答2:


I tried the below and it stopped throwing the error:

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



回答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.



来源:https://stackoverflow.com/questions/40645173/python-regex-find-words-and-emoticons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!