[英]Python Regex: findall Regex to match a string of text to tricky specs and place end result in a list of words
我有一个字符串:
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.
我想对其应用正则表达式,以便它可以生成所需的 output:
['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']
我想使用以下规则创建一个单词列表(全部小写):
**有关详细信息,请参阅所需的 output。
请注意,正则表达式在一个单词中只能允许一个连字符或一个撇号,但每个单词不能超过一个。
我尝试了以下代码:
sample_output_regex = re.findall(r'[a-zA-Z0-9]*[-]?|[\']?[a-zA-Z0-9]*', sample_input.lower())
但是 output 很差:
['', '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', '', '', '']
为了更好地使用正则表达式,我想知道我的正则表达式代码在哪里关闭。 如何更改它以获得我想要的 output。 细节将不胜感激。 例如,当我的正则表达式不要求匹配空格时,为什么空格会被拉为 ''?
关于图案:
您会得到空条目,因为模式[a-zA-Z0-9]*[-]?|[\']?[a-zA-Z0-9]*
中的所有部分都是可选的。
由于交替|
例如not-so
不会是单个匹配项,因为-
之后的部分不会被匹配。
您可能会使用以下方法:
\b[a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)?\b
模式匹配
\b
一个词的边界[a-zA-Z0-9]+
匹配任何列出的范围的 1+ 倍(?:
非捕获组
[-'][a-zA-Z0-9]+
匹配列出范围中的单个-
或'
和 1+)?
关闭组并使其成为可选\b
一个词的边界然后,您可以将所有匹配项转换为小写匹配项。
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)
Output
['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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.