尝试以下方法:
#!python3
import re
line = 'line=a name="12123" adfii 41:05:992 wp=wp2 this is the rate: controlled not max; time=300 loops for the system: process=16.0 sharesize=6b2k'
pattern = r'(\w+)=(\w+|".+?")'
lst = re.findall(pattern, line)
print(lst)
d = dict(lst)
print(d)
print(d['process'])
它会在我的屏幕上打印以下内容:
c:\tmp\___python\njau_ndirangu\so13758903>py a.py
[('line', 'a'), ('name', '"12123"'), ('wp', 'wp2'), ('time', '300'), ('process', '16'), ('sharesize', '6b2k')]
{'line': 'a', 'sharesize': '6b2k', 'time': '300', 'name': '"12123"', 'process': '16', 'wp': 'wp2'}
16
当然可以直接写:
d = dict(re.findall(r'(\w+)=(\w+|".+?")', line))
.findall 返回匹配列表,其中一个匹配表示为以子组为元素的元组(模式内括号中的内容)。
但要小心使用正则表达式。你很容易出错。