首页 > 解决方案 > 通过文本行搜索的正确方法 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() 在第一次命中后继续?任何人都对如何仅对包含所有内容的元素(即“名称”和“连线”)进行正则表达式文本行有任何创意?

标签: pythonregexpandas

解决方案


具有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

推荐阅读