gpt4 book ai didi

python - 通过具有变化模式的文本行进行正则表达式

转载 作者:行者123 更新时间:2023-12-01 06:49:48 25 4
gpt4 key购买 nike

扩展Proper way to search through line of text, re.findall() and re.search() both don't fully work

如果我有以下文本行:

txt = "名称:'红色' 电线:'R' 电线:'B' 名称:'蓝色' 名称:'橙色' 名称:'黄色' 电线:'Y'"

我正在尝试解析这行文本并将每个Wire/Name对填充到数据框中。此文本的问题在于文本行上的 Wire/Name 顺序是可变的。

for line in txt:
line = line.strip()
pairs = re.findall(r'Name *: *\'(?P<name>\w+)\' Wire *: *\'(?P<wire>\w+)\'', content)
if pairs:
for name, wire in pairs:
df = df.append({'Name' : name, 'Wire' : wire}, ignore_index=True)

这种方法的问题是它错过了 Blue/B 对,导致出现以下数据帧。

Name    Wire
red R
yellow Y

我想要实现的数据框是

Name    Wire
red R
blue B
yellow Y

是否可以处理文本模式的变化?

最佳答案

您可以一次只使用一对名称/线并边走边构建各个部分吗?我创建了一个带有一些辅助函数的 Pair 类:

txt = "Name : 'red' Wire : 'R' Wire: 'B' Name : 'blue' Name : 'orange' Name: 'yellow' Wire : 'Y'"
regex = r'((?P<name>Name)|(?P<wire>Wire))\s*?:\s*?\'(?P<value>\w+\')'
pat = re.compile(regex)

class Pair:
name = ''
wire = ''

def populated(self):
return self.name and self.wire

def to_dict(self):
return dict(name=self.name, wire=self.wire)

def __str__(self):
return f'{self.name} {self.wire}'


current_pair = Pair()
all_pairs = []

for x in pat.finditer(txt):
if x.group('name'):
current_pair.name = x.group('value')
elif x.group('wire'):
current_pair.wire = x.group('value')

if current_pair.populated():
all_pairs.append(current_pair)
current_pair = Pair()

for p in all_pairs:
print(p)

您可以更改此代码以跟踪不完整的对(即“橙色”)并决定稍后如何处理它们。

关于python - 通过具有变化模式的文本行进行正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com