简体   繁体   English

使用正则表达式提取字符串中的浮点数

[英]Extracting floating point numbers in a string using regex

I have the following list of strings我有以下字符串列表

List = ['A = -25.47 dBm' , 'B = -47.35 dBm' , 'A = -26.54 dBm' , 'B = -32.35 dBm', 'A = 27.95 dBm' , 'B = -64.11 dBm' , 'A = -45.11 dBm' , 'B = -18.67 dBm']

I want to extract the values of A make a list of that, values of B and make a list of that我想提取 A 的值制作一个列表,B 的值并制作一个列表

I have tried the following我已经尝试了以下

#First I joined the data into a string
S = ' '.join(List)
re.findall(r"A =  ([-+]?\d*\.\d+|\d+) dBm" , S)

which doesn't seem to work这似乎不起作用

Expected Result预期结果

A_list = [-25.47,-26.54, 27.95,-45.11] 
B_list = [-47.35,-32.35,-64.11,-18.67]

You can use re and collections.defaultdict :您可以使用recollections.defaultdict

import re, collections
l = ['A = -25.47 dBm' , 'B = -47.35 dBm' , 'A = -26.54 dBm' , 'B = -32.35 dBm', 'A = 27.95 dBm' , 'B = -64.11 dBm' , 'A = -45.11 dBm' , 'B = -18.67 dBm']
d = collections.defaultdict(list)
for i in l:
  a, b = re.findall('^\w+|[\-\d\.]+', i)
  d[a].append(float(b))

A_list, B_list = d['A'], d['B']

Output:输出:

[-25.47, -26.54, 27.95, -45.11]
[-47.35, -32.35, -64.11, -18.67]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM