我有以下案文:
“当你第一次看到第二次文艺复兴时,它可能看起来很无聊。至少看两次,肯定会看到第二部分。它会改变你对矩阵的看法。人类是发动战争的人吗?人工智能是一件坏事吗?”
我试着用下面的正则表达式把它分成几个句子:
re.split(r'[\.\?\!][\s\n]', text.strip())出于某种原因,它没有删除最后一个问号。我得到的结果如下:
“当你第一次看到第二次文艺复兴时,它可能看起来很无聊”,“至少看它两次,肯定会看第二部分”,“它会改变你对矩阵的看法”,“人类是发动战争的人吗?人工智能是一件坏事吗?”
我尝试修改一下regex,最后添加一个"*“:
re.split(r'[\.\?\!][\s\n]*', text.strip())但我得到的是:
“当你第一次看到第二次文艺复兴的时候,它可能看起来很无聊”,“至少看它两次,肯定会看第二部分”,“它会改变你对矩阵的看法”,“人类是发动战争的人吗”,“人工智能是一件坏事吗?”
我该怎么做?我不能在这里使用NLTK,我只需要使用python 3 regex。
发布于 2018-04-04 07:42:31
从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)用于捕获在演示中使用的正则表达式的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']发布于 2018-04-04 04:28:54
您将获得最后一个元素为空,因为regex [\.\?\!][\s\n]*匹配在该?上执行拆分操作的最后一个?,该?为您提供两个字符串--一个在该?的左边,另一个在右边。最后一个?右边的字符串是一个空字符串,因此得到数组的最后一个空元素。
您可以使用以下regex获得匹配,而不是拆分:
[^.?!]+参见这里的Python代码输出
https://stackoverflow.com/questions/49642756
复制相似问题