python - 通过文本行搜索的正确方法 re.findall() 和 re.search() 都不能完全工作
问题描述
我的问题有点奇怪,也许有人可以提供一些指导。我有一行文本需要搜索并提取多个重复出现的字符串来填充数据框。鉴于以下行:
txt = "Name : 'red' Wire : 'R' Name : 'blue' Wire: 'B' Name : 'orange' Name: 'yellow' Wire : 'Y'"
我想通过正则表达式并仅提取完整的名称/电线对(在此示例中不是Orange
)。
预期产出
Name Wire
red R
blue B
yellow Y
代码
for line in txt:
line = line.strip()
a = re.search(r' Name : \'((?:(?![(]).)*)\'', line)
if a:
b = re.search(r' Wire : \'((?:(?![(]).)*)\'', line)
if b:
df = df.append({'Name' : a.group(1), 'Wire' : b.group(1)}, ignore_index=True)
此代码产生以下df:
Name Wire
red R
这种行为是预期的,因为re.search()
它只会运行到第一次找到有问题的项目。
好的,re.search()
不会工作,所以我会尝试re.findall()
:
for line in txt:
line = line.strip()
a = re.findall(r' Name : \"((?:(?![(]).)*)\"', line)
if a:
b = re.findall(r' Wire : \"((?:(?![(]).)*)\"', line)
if b:
df = df.append({'Name' : a, 'Wire' : b}, ignore_index=True)
这将吐出以下df:
Name Wire
['red','blue','orange','yellow'] ['R','B','Y']
这个数据框的问题是,现在我们不再知道什么Name
与什么相关联Wire
。如果 re.search() 没有到达 txt 行的末尾,是否有任何方法可以让 re.search() 在第一次命中后继续?任何人都对如何仅对包含所有内容的元素(即“名称”和“连线”)进行正则表达式文本行有任何创意?
解决方案
具有re.finditer
功能和特定的正则表达式模式:
import pandas as pd
import re
txt = "Name : 'red' Wire : 'R' Name : 'blue' Wire: 'B' Name : 'orange' Name: 'yellow' Wire : 'Y'"
pat = re.compile(r"Name\s*:\s*'(?P<Name>[^']+)'\s+Wire\s*:\s*'(?P<Wire>[^']+)'")
items = [m.groupdict() for m in pat.finditer(txt)]
df = pd.DataFrame(items)
print(df)
(?P<Name>[^']+)
-被“翻译”为对象的命名子组m.groupdict()
输出:
Name Wire
0 red R
1 blue B
2 yellow Y
推荐阅读
- php - 使用 (preg_replace) 我认为我的语法有点不对劲。我是否需要退出某事或其他
- git - Git 自动合并提交消息
- php - MySQL 使用变量更新表?
- python - Django Test 正在使用 manage.py test 应用程序,但不适用于 manage.py test
- python - 如何使用 seaborn / matplotlib 为条形图的标签名称添加背景颜色
- bash - 将简单目标添加到 cmake 生成的 makefile
- c# - “收藏已修改;System.Data.TypedTableBase<> 中的枚举操作可能无法执行
- python-3.x - 无法在 Google Colab 中将 Pytorch 模型保存到 Google Drive?
- python - 如何从图像中提取平滑的骨架
- loops - Ansible - 在列表产品上循环时枚举列表(嵌套循环)