【发布时间】:2021-04-25 17:04:06
【问题描述】:
我正在尝试从包含测试结果的文本文件创建字典。
文本文件如下所示:
NETAPP-MIB::enclTempSensorsCurrentTemp.1 = STRING: 29C (84F) ambient, 36C (96F), 36C (96F), 36C (96F), 36C (96F), 36C (96F), 57C (134F), 37C (98F), 57C (134F), 44C (111F), 59C (138F), 40C (104F), 45C (113F), 58C (136F), 42C (107F)
我的目标是获取所有包含带有字母 C 的数字的结果。 但我设法只得到第一个值
例如这是我得到的:
{'TEST sensor num 0': '29C'}
这是我的代码:
import re
def get_names(ip):
"""Get the server name according the IP address"""
names = {"TEST": "10.205.110.226", "TEST2": "10.205.111.216"}
if ip in names.values():
for key, val in names.items():
if ip == val:
return key
else:
return f"No Recognized unit {ip}"
def get_temps_servers():
""" Return A dict mapping from sensor name to sensor value """
result = {}
count = 0
with open("test.txt", "r") as newdata:
text = newdata.read()
for ip in online_server:
name = get_names(ip)
for c in re.findall(r"^.*?(\d+C)", text, flags=re.M):
result[f"{name} sensor num {count}"] = c
count = count + 1
print(result)
return result
global online_netapp
online_server = ["10.205.110.226"]
get_temps_servers()
我想要得到的是像这个例子这样的结果:
{'TEST sensor num 0': '29C', 'TEST sensor num 1': '36C', 'TEST sensor num 2': '36C'}
只要有一个带有 C 的数字,就会这样继续下去。
我做错了什么?
【问题讨论】:
-
正则表达式
r"^.*?(\d+C)"只能匹配一个字符串一次,因为^表示字符串的开头,而字符串只有一个开头。应用.findall并没有帮助,因为只有一个可能的匹配:从字符串开头开始的那个。.*?尝试在(\d+C)之前匹配尽可能少的字符,这要感谢?;但它仍然只匹配一个特定数量的字符。
标签: python dictionary python-re