gpt4 book ai didi

python - 使用Python将包含一些关键字的字符串分成列表

转载 作者:太空宇宙 更新时间:2023-11-04 09:16:23 24 4
gpt4 key购买 nike

我正在尝试在 Ubuntu 中解析/etc/network/interfaces 配置文件,因此我需要将字符串分成字符串列表,其中每个字符串都以给定关键字之一开头。

根据手册:

The file consists of zero or more "iface", "mapping", "auto", "allow-" and "source" stanzas.

所以如果文件包含:

auto lo eth0
allow-hotplug eth1

iface eth0-home inet static
address 192.168.1.1
netmask 255.255.255.0

我想获取列表:

['auto lo eth0', 'allow-hotplug eth1', 'iface eth0-home inet static\n address...']

现在我有这样的功能:

def get_sections(text):
start_indexes = [s.start() for s in re.finditer('auto|iface|source|mapping|allow-', text)]
start_indexes.reverse()
end_idx = -1
res = []
for i in start_indexes:
res.append(text[i: end_idx].strip())
end_idx = i
res.reverse()
return res

但这并不好...

最佳答案

您可以在一个正则表达式中完成:

>>> reobj = re.compile("(?:auto|allow-|iface)(?:(?!(?:auto|allow-|iface)).)*(?<!\s)", re.DOTALL)
>>> result = reobj.findall(subject)
>>> result
['auto lo eth0', 'allow-hotplug eth1', 'iface eth0-home inet static\n address 192.168.1.1\n netmask 255.255.255.0']

解释:

(?:auto|allow-|iface)   # Match one of the search terms
(?: # Try to match...
(?! # (as long as we're not at the start of
(?:auto|allow-|iface) # the next search term):
) #
. # any character.
)* # Do this any number of times.
(?<!\s) # Assert that the match doesn't end in whitespace

当然,您也可以按照评论中的要求将结果映射到元组列表中:

>>> reobj = re.compile("(auto|allow-|iface)\s*((?:(?!(?:auto|allow-|iface)).)*)(?<!\s)", re.DOTALL)
>>> result = [tuple(match.groups()) for match in reobj.finditer(subject)]
>>> result
[('auto', 'lo eth0'), ('allow-', 'hotplug eth1'), ('iface', 'eth0-home inet static\n address 192.168.1.1\n netmask 255.255.255.0')]

关于python - 使用Python将包含一些关键字的字符串分成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8910130/

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