【发布时间】:2022-01-11 23:56:27
【问题描述】:
我的句子结构为“Name has digit1 word1, digit2 word2, ..., and digitN wordN”,其中子模式“digit word”的数量因句子而异,因此不确定。最后一个子模式之前有一个“and”。例如“爱丽丝有 1 个苹果、2 个香蕉、……和 6 个橙子。”
如何在 python 中使用正则表达式提取这些数字和单词?我希望输出如下:
姓名,
| Digit | Word |
|---|---|
| digit1 | word1 |
| digit2 | word2 |
| ... | ... |
| digitN | wordN |
我尝试了以下方法:
s = 'Alice has 1 apple, 2 bananas, and 3 oranges.'
import re
matches = re.finditer(r'([Aa-z]+) has (\d) ([a-z]+)( and)*', s)
for match in matches:
print(match.groups())
但这只会给我('Alice','1','apple',None),缺少'2','bananas','3','oranges'。
【问题讨论】:
-
嘿我做了你建议的改变。请看一看!