[英]How to extract specific information from a file in python
I have a file with following format: 我有一个格式如下的文件:
device={
id=1
tag=10
name=device1
}
device={
id=2
tag=20
name=device2
}
device={
id=3
tag=30
name=device3
}
So let's say I am only interested in device with id=2
and I want to extract its tag number(this is configurable and will be changed from some other code). 所以,假设我只对
id=2
设备感兴趣,并且我想提取其标签号(这是可配置的,并将从其他代码更改)。 So I need to extract tag number of the device id 2. How can I do this in python. 所以我需要提取设备ID 2的标签号。我怎么能在python中做到这一点。 I have done following:
我做了以下事情:
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
Thanks 谢谢
With re.search function: 使用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))
The output: 输出:
20
f.read()
- reads the file contents (as text) f.read()
- 读取文件内容(作为文本)
r'' + id_num + '\\s+tag=([0-9]+)'
- constructing regex pattern, so it would become id=2\\s+tag=([0-9]+)
where \\s
is one or many whitespace characters(including newlines) and ([0-9]+)
is the 1st captured group containing tag number r'' + id_num + '\\s+tag=([0-9]+)'
- 构造正则表达式模式,因此它将变为id=2\\s+tag=([0-9]+)
其中\\s
是一个或多个空白字符(包括换行符)和([0-9]+)
是包含标记号的第一个捕获组
tag_num.group(1)
- extracting the value of the 1st captured/parenthesized group 1
from the match object tag_num
tag_num.group(1)
- 从匹配对象tag_num
提取第一个捕获/带括号的组1
的tag_num
You can read the next line using line.readline()
try to use this code: 您可以使用
line.readline()
阅读下一行,尝试使用此代码:
ID='id=2'
with open("file.txt") as file:
while True:
line = file.readline()
if line.strip() == ID:
nextline = file.readline()
result = nextline.strip().split('=')[1]
if line == '':
break
with open("") as file:
#print file.read()
for line in file:
#print line.split()
if line.strip()==ID:
d=file.next() #reads next line
print d.split('=')[1]
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.