python - 正则表达式提取从和到日期?
问题描述
我正在尝试使用正则表达式从单独的组中提取和提取年份,但由于格式不同而无法提取,如下所示。应用正则表达式:([0-9]+)-?([0-9a-z]+)
以下是需要提取的完整数据:
['165-180 A.D.',
'1520-unknown',
'1665',
'1817-1923',
'Late 1800s',
'1918-1920',
'1957-1958',
'2009']
上面的正则表达式提取165,1520,166在组1和2019,unknown, 5在组2。需要把1665放在group1和group2正则表达式中的空白字段。同样,group1 中的 1800 年代后期
wp_page = requests.get("https://www.washingtonpost.com/graphics/2020/local/retropolis/coronavirus-deadliest-pandemics/")
wp_soup = bs(wp_page.content, 'html.parser')
[names.get_text() for names in wp_soup.find_all('h5')][0:-2]
wp_year_from_list=[]
wp_year_to_list=[]
wp_year_regex=re.compile('([0-9]+)-?([0-9a-z]+)')
for names in wp_soup.find_all('h5'):
if (wp_year_regex.search(names.text)!= None):
wp_year_from_list.append(wp_year_regex.search(names.text).group(1))
wp_year_to_list.append(wp_year_regex.search(names.text).group(2))```
解决方案
根据您的要求,您需要?
为第二组添加量词。所以你的正则表达式看起来像:
([0-9]+)-?([0-9a-z]+)?
^^
上述正则表达式的解释:
([0-9]+)
- 捕获数字 1 次或更多时间的捕获组。
-?
- 匹配连字符字面上的零次或 1 次。
([0-9a-z]+)?
- 第二个捕获组捕获数字和字母1次或多次,该组可以出现0次或1次。
您可以在此处找到上述正则表达式的演示。
推荐阅读
- permissions - Keycloak 在资源和权限方面可以扩展多远?
- python - 为每个网格单元创建粒子位置列表
- python - 如何通过 python 程序从存储在 .txt 文件中的 HTML/JS 代码中的单词列表中查找单词?
- facebook - 如何通过 Graph API 为即时游戏上传存档?
- javascript - 仅当按钮较早关闭时 Selenium python 才展开和折叠
- reactjs - 在 useState() 之后 React Native 不更新 UI
- r - ggplot2(R)中的十六进制颜色未正确绘制
- android - 在 android 开关材料中插入文本
- reactjs - ag-grid react cellEditor 格式
- microsoft-graph-api - 从组创建团队失败并出现异常