fsc*_*ore 1 python regex nlp emoticons
这是表情符号列表:http://en.wikipedia.org/wiki/List_of_emoticons 我想形成一个正则表达式,检查句子中是否存在任何这些表情符号.例如,"嘿,我很好:)"或"我生气和悲伤:(但是维基百科上的列表中有很多表情符号,所以想知道如何才能完成这项任务.我是regex的新手.&蟒蛇.
>>> s = "hey there I am good :)"
>>> import re
>>> q = re.findall(":",s)
>>> q
[':']
Run Code Online (Sandbox Code Playgroud)
我看到了两种解决问题的方法:
以下是一些代码,可以帮助您开始使用这两种方法:
# approach 1: pattern for "generic smiley"
eyes, noses, mouths = r":;8BX=", r"-~'^", r")(/\|DP"
pattern1 = "[%s][%s]?[%s]" % tuple(map(re.escape, [eyes, noses, mouths]))
# approach 2: disjunction of a list of smileys
smileys = """:-) :) :o) :] :3 :c) :> =] 8) =) :} :^)
:D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D""".split()
pattern2 = "|".join(map(re.escape, smileys))
text = "bla bla bla :-/ more text 8^P and another smiley =-D even more text"
print re.findall(pattern1, text)
Run Code Online (Sandbox Code Playgroud)
两种方法都有优点,缺点和一些一般限制.你总会有误报,就像数学术语一样18^P.在表达式周围放置空格可能会有所帮助,但是你不能匹配表情符号后面的表情符号.第一种方法更强大,并且捕获第二种方法不匹配的表情符号,但只要它们遵循某种模式.您可以对"东方"表情使用相同的方法,但它不适用于严格对称的表情,例如=^_^=,因为这不是常规语言.另一方面,第二种方法更容易扩展新的表情,因为您只需将它们添加到列表中.