我有一个格式如下的文件:
device={
id=1
tag=10
name=device1
}
device={
id=2
tag=20
name=device2
}
device={
id=3
tag=30
name=device3
}
假设我只对具有 id=2
的设备感兴趣,并且我想提取它的标签号(这是可配置的,将从其他一些代码中更改)。所以我需要提取设备 id 2 的标签号。我如何在 python 中执行此操作。我做了以下工作:
ID='id=2'
with open("file.txt") as file:
for line in file:
if line.strip() == ID:
#Here I do not know what to write
# to extract 20
谢谢
最佳答案
与 re.search功能:
import re
with open('file.txt', 'r') as f:
id_num = 'id=2'
tag_num = re.search(r'' + id_num + '\s+tag=([0-9]+)', f.read())
print(tag_num.group(1))
输出:
20
f.read()
- 读取文件内容(作为文本)r'' + id_num + '\s+tag=([0-9]+)'
- 构造正则表达式模式,因此它将变为id=2\s+tag=([0-9]+)
其中\s
是一个或多个空白字符(包括换行符)和([0-9]+)
是包含 tag number 的第一个捕获组
tag_num.group(1)
- 从 match 中提取第一个捕获/带括号的组1
的值对象tag_num
关于python - 如何从python中的文件中提取特定信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922513/