[英]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.