我试图在用户消息中找到“笑声词”或类似的词,如hahaha、hihihi、hueheu。我目前的做法如下:
>>> substring_list = ['ha', 'ah', 'he', 'eh', 'hi', 'ih', 'ho', 'hu', 'hue']
>>> pattern_core = '|'.join(substring_list)
>>> self.regex_pattern = re.compile(r'\b[a-z]*(' + pattern_core + r'){2,}[a-z]*\b', re.IGNORECASE)当涉及到打字时(例如,[a-z]* ),ahhahah允许有一定的回旋余地。原则上,这是相当好的工作。问题是,它需要保持在这样的意义上,即substring_list需要更新以匹配新形式的“笑词”(例如,添加xi);“笑词”似乎在国家间有相当大的差异。
现在,我想知道我是否可以在不知道单个模式的情况下,找到基于重复模式的单词(例如,2-4)。例如,hurrhurr包含作为重复模式的hurr。在理想情况下,我可以(a)匹配hurrhurr和(b)识别核心模式hurr。我不知道正则表达式是否能做到这一点。
发布于 2015-11-14 06:58:02
这个regex会做到这一点:
\b[a-z]*?([a-z]{2,}?)\1+[a-z]*?\b用法:
self.regex_pattern = re.compile(r'\b[a-z]*?([a-z]{2,}?)\1+[a-z]*?\b', re.IGNORECASE)要点与你所做的类似,但“核心”却不同。regex的核心是这段:
([a-z]{2,}?)\1+逻辑是找到一个由2个或多个字母组成的组,然后匹配同一组(\1)一次或多次。
发布于 2015-11-14 07:00:48
在理想情况下,我可以(a)匹配hurrhurr和(b)识别核心模式hurr。我不知道正则表达式是否能做到这一点。
import re
string = """hahaha, huehue, heehee,
axaxaxax, x the theme, ------, hhxhhxhhx,
bananas, if I imagine, HahHaH"""
pattern = r"""
(
\b #Match a word boundary...
(
[a-z]{2,}? #Followed by a letter, 2 or more times, non-greedy...
) #Captured in group 2,
\2+ #Followed by whatever matched group 2, one or more times...
\b #Followed by a word boundary.
) #Capture in group 1.
"""
results = re.findall(pattern, string, re.X|re.I)
print(results)
--output:--
[('hahaha', 'ha'), ('huehue', 'hue'), ('heehee', 'hee'), ('axaxaxax', 'ax'), ('hhxhhxhhx', 'hhx'), ('HahHaH', 'Hah')]https://stackoverflow.com/questions/33705919
复制相似问题