我想读取文本文件并找到下面文本中以 5 开头的单词。
“状态”:“确定”}]、“PhysicalLocationString”:“rack1/chassis_u1/cpu0/pcie_slot3”、“Physloc”:“0003000101010005”、“PlaceholderNetworkDeviceFunctions”:[{“FC HBA 1”:“51: 40:2E:C0:01:C9:53:E8"}, {"FC HBA 2": "51:40:2E:C0:01:C9:53:EA"}]}}, "零件编号": "P9D94A", "序列号": "MY57470DS8", "状态": {"Health": "OK", "HealthRollup": "OK", "State": "Enabled"}}
我在另一个文件中的输出应该是
51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA
这是我的代码:
import re
import sys
import os
#get line
with open('/root/SDFlex/work/cookbooks/ilorest/files/OP.txt', 'r') as file:
for line in file:
re.findall(r'\b[s]:\w+', line)
matchedLine = line
break
#and write it to the file
with open('/root/SDFlex/work/cookbooks/ilorest/files/file.txt', 'w') as
file:
file.write(matchedLine)
请帮忙
最佳答案
使用模式
pattern = '"(5[^"]+)"'
re.findall(pattern, your_string)
它将搜索引号 "
,后跟 5,后跟除引号之外的任何内容,然后以引号结束。分组将提取您想要的数字。
关于Python:使用python从一行中提取以数字开头的匹配单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644378/