【发布时间】:2012-02-13 04:07:51
【问题描述】:
我正在尝试在 Ubuntu 中解析 /etc/network/interfaces 配置文件,因此我需要将字符串划分为字符串列表,其中每个字符串都以给定关键字之一开头。
根据手册:
该文件由零个或多个“iface”、“mapping”、“auto”、“allow-”和“source”节组成。
所以如果文件包含:
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
但这并不好......
【问题讨论】:
-
或者,您可以使用confparse 之类的东西,它显然支持网络接口文件。
-
您可以通过直接从 start_indexes 中提取切片来大大简化此代码。