我有一个像这样的输出字符串:
read : io=131220KB, bw=14016KB/s, iops=3504, runt= 9362msec
我只想提取一个数值进行计算,比如 iops。我是这样处理的:
if 'read ' in key:
my_read_iops = value.split(",")[2].split("=")[1]
result['test_details']['read'] = my_read_iops
但是我正在阅读的一些字符串存在轻微的不一致,并且我的代码变得非常复杂和冗长。因此,除了手动计算逗号与“=”字符的数量之外,还有什么更好的方法来处理这个问题呢?
您可以使用正则表达式
\s*
来处理不一致的间距,它匹配零个或多个空格:
import re
s = 'read : io=131220KB, bw=14016KB/s, iops=3504, runt= 9362msec'
for m in re.finditer(r'\s*(?P<name>\w*)\s*=\s*(?P<value>[\w/]*)\s*', s):
print(m.group('name'), m.group('value'))
# io 131220KB
# bw 14016KB/s
# iops 3504
# runt 9362msec
使用组名称,您可以从列名称列表构造模式字符串,然后执行以下操作:
names = ['io', 'bw', 'iops', 'runt']
name_val_pat = r'\s*{name}\s*=\s*(?P<{group_name}>[\w/]*)\s*'
pattern = ','.join([name_val_pat.format(name=name, group_name=name) for name in names])
# '\s*io\s*=\s*(?P<io>[\w/]*)\s*,\s*bw\s*=\s*(?P<bw>[\w/]*)\s*,\s*iops\s*=\s*(?P<iops>[\w/]*)\s*,\s*runt\s*=\s*(?P<runt>[\w/]*)\s*'
match = re.search(pattern, s)
data_dict = {name: match.group(name) for name in names}
print(data_dict)
# {'io': '131220KB', 'bw': '14016KB/s', 'runt': '9362msec', 'iops': '3504'}
这样,你只需要更改
names
并保持顺序正确即可。
如果我是你,我会使用 regex(正则表达式)作为首选。
import re
s= "read : io=131220KB, bw=14016KB/s, iops=3504, runt= 9362msec"
re.search(r"iops=(\d+)",s).group(1)
通过这段Python代码,我找到了以“iops=”开头并继续数字表达式至少1位的字符串模式。我使用圆括号提取了目标字符串(3504)。 您可以从
找到有关正则表达式的更多信息https://docs.python.org/3.6/library/re.html#module-re
正则表达式是一种功能强大的语言,可以用简单的语法进行复杂的模式匹配。
尝试
rom重新导入匹配 string = '读取:io=131220KB,bw=14016KB/s,iops=3504,runt=9362msec' iops = match(r'.+(iops=)([0-9]+)', string).group(2)
from re import match
string = 'read : io=131220KB, bw=14016KB/s, iops=3504, runt= 9362msec'
iops = match(r'.+(iops=)([0-9]+)', string).group(2)
iops
'3504'