正则表达式构造从文本Python中获取句子

2024-05-19 10:08:32 发布

您现在位置:Python中文网/ 问答频道 /正文

句子将是一系列字符:

  1. 以字符!?(但不包括)结尾。或者文件的结尾
  2. 排除两端的空白,以及
  3. 不是空的

我有一个包含以下文本的文件:

this is the\nfirst sentence. Isn't\nit? Yes ! !! This \n\nlast bit :) is also a sentence, but \nwithout a terminator other than the end of the file\n

根据上述定义,其中有四个“句子”:

  • 第一句:this is the\nfirst sentence
  • 第二句:Isn't\nit
  • 第三句:Yes
  • 第四句:This \n\nlast bit :) is also a sentence, but \nwithout a terminator other than the end of the file

请注意:

  • 这些句子不包括他们的终结符。你知道吗
  • 最后一句话不是以字符结尾,而是以文件结尾结束。你知道吗
  • 句子可以跨越文件的多行。你知道吗

这就是我目前拥有的(.*\n+),我不知道如何改进它。你知道吗

请我需要你的帮助,一个正则表达式,解构成上面的文字,并返回一个列表。事先感谢你的帮助。你知道吗


Tags: 文件theis结尾bitthis字符sentence
2条回答

下面的内容不是每个人都适用的,但它适用于您的特定输入。您可以进一步调整此表达式:

([^!?.]+)[!?.\s]*(?![!?.])

参见regex demo。你知道吗

详细信息:

  • ([^!?.]+)-捕获组1匹配除!?.以外的1个或多个字符
  • [!?.\s]*-0或更多!?.,空格
  • (?![!?.])-后面不跟!?.。你知道吗

在Python中,您需要将它与re.findall一起使用,后者只获取捕获组捕获的子字符串:

import re
rx = r"([^!?.]+)[!?.\s]*(?![!?.])"
s = "this is the\nfirst sentence. Isn't\nit? Yes ! !! This \n\nlast bit :) is also a sentence, but \nwithout a terminator other than the end of the file\n"
sents = re.findall(rx, s)
print(sents)
# => ['this is the\nfirst sentence', 
      "Isn't\nit", 
      'Yes ', 
      'This \n\nlast bit :) is also a sentence, but \nwithout a terminator other than the end of the file\n'
     ]

Python demo

试试这个:

re.split('(\!\s\!+)|\.|\?',s)
['this is the\nfirst sentence', " Isn't\nit", ' Yes ', ' This \n\nlast bit :) is also a sentence, but \nwithout a terminator other than the end of the file\n']

相关问题 更多 >

    热门问题