Python Regex: findall Regex将文本字符串匹配到复杂的规格,并将最终结果放置在单词列表中.<



我有一个字符串:

sample_input = """
This film is based on Isabel Allende's not-so-much-better novel. I hate Meryl
Streep and Antonio Banderas (in non-Spanish films), and the other actors,
including Winona, my favourite actress and Jeremy Irons try hard to get over
such a terrible script.

我想对它应用正则表达式,以便它可以产生所需的输出:

['this', 'film', 'is', 'based', 'on', 'isabel', "allende's", 'not-so', 'much-better', 'novel', 'i', 'hate', 'meryl', 'streep', 'and', 'antonio', 'banderas', 'in', 'non-spanish', 'films', 'and', 'the', 'other', 'actors', 'including', 'winona', 'my', 'favourite', 'actress', 'and', 'jeremy', 'irons', 'try', 'hard', 'to', 'get', 'over', 'such', 'a', 'terrible', 'script']

我想用以下规则创建一个单词列表(全部小写):

  1. 一个单词必须以单个字母或数字开头和结尾。
  2. 在一个单词
  3. 中只能有一个连字符(-)或一个撇号(')
  4. 如果违反1或2则为新词

**详细信息请参见所需输出

请注意,正则表达式只允许在一个单词中使用一个连字符或一个撇号,但每个单词不能超过一个。

我尝试了以下代码:

sample_output_regex = re.findall(r'[a-zA-Z0-9]*[-]?|[']?[a-zA-Z0-9]*', sample_input.lower())

但是输出很差:

['', 'this', '', 'film', '', 'is', '', 'based', '', 'on', '', 'isabel', '', 'allende', '', "'s", '', 'not-', 'so-', 'much-', 'better', '', 'novel', '', '', 'i', '', 'hate', '', 'meryl', '', 'streep', '', 'and', '', 'antonio', '', 'banderas', '', '', 'in', '', 'non-', 'spanish', '', 'films', '', '', '', 'and', '', 'the', '', 'other', '', 'actors', '', '', 'including', '', 'winona', '', '', 'my', '', 'favourite', '', 'actress', '', 'and', '', 'jeremy', '', 'irons', '', 'try', '', 'hard', '', 'to', '', 'get', '', 'over', '', 'such', '', 'a', '', 'terrible', '', 'script', '', '', '']

在努力得到更好的正则表达式,我想知道我的正则表达式代码是关闭。我如何改变它来得到我想要的输出。详细情况将不胜感激。例如,当我的regex不要求匹配空格时,为什么空格被拉出为"?

关于模式:

模式[a-zA-Z0-9]*[-]?|[']?[a-zA-Z0-9]*中的所有部分都是可选的,因此得到空条目。

由于|的交替,例如not-so将不是单个匹配,因为-之后的部分将不匹配。


您可以使用如下方法:

b[a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)?b

模式匹配

  • bA字边界
  • [a-zA-Z0-9]+匹配1+次所列范围
  • (?:非捕获组
    • [-'][a-zA-Z0-9]+匹配单个-'和1+所列范围
  • )?关闭组并使其为可选
  • bA字边界

regex演示

那么您可以将所有匹配项转换为小写。

import re
sample_input = """
This film is based on Isabel Allende's not-so-much-better novel. I hate Meryl
Streep and Antonio Banderas (in non-Spanish films), and the other actors,
including Winona, my favourite actress and Jeremy Irons try hard to get over
such a terrible script."""
res = [x.lower() for x in re.findall(r"b[a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)?b", sample_input)]
print(res)

输出
['this', 'film', 'is', 'based', 'on', 'isabel', "allende's", 'not-so', 'much-better', 'novel', 'i', 'hate', 'meryl', 'streep', 'and', 'antonio', 'banderas', 'in', 'non-spanish', 'films', 'and', 'the', 'other', 'actors', 'including', 'winona', 'my', 'favourite', 'actress', 'and', 'jeremy', 'irons', 'try', 'hard', 'to', 'get', 'over', 'such', 'a', 'terrible', 'script']

最新更新