python - 使用正则表达式提取数据
问题描述
text='''
Consumer Price Index:
+0.3% in Aug 2020
Unemployment Rate:
+2.4% in Aug 2020
'''
使用正则表达式将数据提取到元组列表中,例如
[('Consumer Price Index', '+0.2%', 'Aug 2020'), ...]
并返回元组列表
我尝试了几次
re.findall( , text)
有人有好主意吗?
解决方案
我将首先拆分字符串'\n\n'
以将它们分成单独的部分(以避免混淆),然后在每个部分上运行正则表达式以提取组。
看这个例子:
import re
text = '''
Consumer Price Index:
+0.2% in Sep 2020
Unemployment Rate:
+7.9% in Sep 2020
'''
sections = text.split('\n\n')
results = []
for section in sections:
pattern = re.compile(r'\s+([\w\s]+):\n.+(\+.+) in ([\w\d\s]+)')
matches = pattern.match(section)
if matches:
results.append(matches.groups())
print(results)
输出:
[
('Consumer Price Index', '+0.2%', 'Sep 2020'),
('Unemployment Rate', '+7.9%', 'Sep 2020')
]
更新:
这是一个解决方案,re.findall
但就像我说的那样,根据text
结构的不同,可能存在不一致。为了安全起见,您应该分而治之。
import re
text = '''
Consumer Price Index:
+0.2% in Sep 2020
Unemployment Rate:
+7.9% in Sep 2020
'''
sections = text.split('\n\n')
pattern = re.compile(r'\s+([\w\s]+):\n.+(\+.+) in ([\w\d\s]+)\n')
results = pattern.findall(text)
print(results)
推荐阅读
- android - kotlinx.coroutines 的 ProGuard 警告
- python-3.x - 如何正确定位元素以单击python中的href元素
- r - 使用 dplyr::mutate 对 R 中的百分比差异计算感到困惑
- javascript - 使用 webpack-dev-server 查看本地依赖项
- sql - 有没有办法添加我们自动获取日期的日期差异值?
- javascript - Nodemon ts-node 无法监视 JavaScript 更改
- amazon-redshift - Redshift XN 排序成本
- ios - UITableViewDiffableDataSource:如何获取节索引
- mongodb - MongoDB:多个因果一致会话中的最新一个
- python - 类型对象“Food101”没有属性“load_data”