2016-09-27 36 views
1

我想从下面的twitter文本中提取困惑的标点符号(任意数字的组合!)。python:用正则表达式提取困惑的标点符号

string4 = 'on my god!!!!,I think he is right?!, but what about he!??, but me !!??, yes !?!?, and my god ?!?.' 

我用下面的正则表达式:

p_excitement = re.compile(r'!{1,}\?{1,}') 

m = p_excitement2.findall(string4) 

但结果是:

['!??', '!!??', '!?', '!?', '!?'] 

这是错误的。我希望得到以下结果(请注意,我想任何疑惑标点符号不只是下面的文字):

['?!', '!??', '!!??', '!?!?', '?!?'] 

感谢您的帮助!

+0

普莱斯考虑接受所提供的正确答案第一。 –

回答

1

你可以去为新regex module和使用

(([?!.])\2{1,})(*SKIP)(*FAIL)|[?!.]+ 

a demo here


Python

import regex as re 

string = "on my god!!!!,I think he is right?!, but what about he!??, but me !!??, yes !?!?, and my god ?!?." 

rx = re.compile(r'(([?!.])\2{1,})(*SKIP)(*FAIL)|[?!.]+') 
matches = [match.group(0) 
      for match in rx.finditer(string) 
      if match] 
print(matches) 
# ['?!', '!??', '!?!?', '?!?.'] 
+0

感谢您的意见。我更新了我的问题,其中'!!!'被添加,我不想提取! – tktktk0711

+0

@ tktktk0711:为什么不呢?这里的规则是什么? – Jan

+0

感谢您的意见@Jan。我很抱歉忘了添加!!!到'!!!'之后的文字在文中。我只是想从文字 – tktktk0711

1

您可以使用

[?!]*(?:\!+\?+|\?+\!+)+[?!]* 

regex demo

详细

  • [?!]* - 零个或更多?!
  • 符号
  • (?:\!+\?+|\?+!+)+ - 1个或多个的
    • \!+\?+ - 1+ !秒,然后用1 + ?小号
    • | - 或
    • \?+!+ - 1+ ? s followed with 1+!单曲
  • [?!]* - 零个或更多?!
  • 符号

Python demo

import re 
p = re.compile(r'[?!]*(?:\!+\?+|\?+\!+)+[?!]*') 
s = "on my god!!!!,I think he is right?!, but what about he!??, but me !!??, yes !?!?, and my god ?!?." 
print(p.findall(s)) 
# => ['?!', '!??', '!!??', '!?!?', '?!?'] 
+0

供参考:'(?:\!+ \?+ | \?+ \!+)+'部分*需要连续的'!'和'?'s或' ?和'!'在序列中出现至少一次以匹配它。由于正则表达式在're.findall'中使用,所以'(?:...)'非捕获组很方便。 –

+1

感谢@WiktorStribiżew,看起来你是对的(?:\!+ \?+ | \?+!+)+。我正在确认它。 – tktktk0711

1

正则表达式:

((?:\!+\?+)+!*|(?:\?+!+)+\?*) 
  • (?:\!+\?+)+!*!开始,并且可以结束于?
  • (?:\?+!+)+\?*[!?]任意组合,与?开始和[!?]任何组合可以结束于!

Live demo

+0

谢谢@revo,我也在确认它 – tktktk0711