从split() 函数的性质看来,separator(或delimiter)将一个字符串分成两个。当分隔符出现在字符串的开始(或结束)位置时,可能会发生这种在拆分处理过程中创建空字符串副产品的特殊行为。
为了避免或删除这种类型的空字符串,您可以使用其他函数:filter() 函数来删除空字符串,或者 re.match() 和 re.findall() 等。如下所示,以避免空字符串元素被拆分。
分隔符的正则表达式
[\.\?\!](?:[\s]+|$)
- 使用filter() 函数从拆分中删除空字符串元素,或使用re.findall() 函数捕获除separator 之外的字符串。
ss="""The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war? Is AI a bad thing?"""
splt= re.split(r"[\.\?\!](?:[\s]+|$)",ss)
splt=list(filter(None,splt))
print(splt)
regs= re.compile(r'((?:(?).)*)[\.\?\!](?:[\s]+|$)')
match= regs.findall(ss)
print(match)
Demo 用于捕获findall() 中使用的正则表达式
((?:(?).)*)[\.\?\!](?:[\s]+|$)
脚本执行结果是
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']