python - 如何从python中的文件中提取特定信息

标签 python file

我有一个格式如下的文件:

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/

相关文章:

Windows 中的 Python 套接字问题 : socket. MSG_DONTWAIT

python - 在 Python 中动态创建具有自定义值的枚举?

python - 从 Python 3 调用 Windows API 时句柄无效

python - 我可以使用 Python 3 'with open(filename, mode) as file:' 并将其保存在对象中以向其发送事件吗?

php - 如何在php中使文件下载仅将文件路径保存在数据库中

ios - 如何从文本文件创建一个 NSNumbers 数组?

python - (Python 3) imaplib 从 .txt 文件登录

python - 使用 wxPython 返回多个文件路径以在另一个函数中使用

linux - 有没有办法在 CentOS 中计算每秒文件中添加的行数?

python - 如何重新排序数据帧的顺序以匹配第二个数据帧的顺序?