首页 > 解决方案 > 用python从不规则值中提取数字

问题描述

我有如下数据:

Format,Message,time
A,gn@2 ab@1 yl@5 rd@20 pp@40,3
B,w:w23w4w5w6w7gn@3 gn@7 yl@20 ss@25 rd@50,21
C,cc@1 fgn@4 yl@9 rd@20,22
D,rg@1 fedsf@5 rww@10 yl@20 rd@26,30

我的预期结果是提取 gn,yl 和 rd 之后的数字

Format,Message,time,gn,yl,rd
A,gn@2 ab@1 yl@5 rd@20 pp@40,3,2,5,20
B,w:w23w4w5w6w7gn@3 an@7 yl@20 ss@25 rd@50,21,3,20,50
C,cc@1 fgn@4 yl@9 rd@20,22,4,9,20
D,rg@1 fedsf@5 rww@10 yl@20 rd@26,30,0,20,26

到目前为止,我能够获得 yl 和 rd,但我无法提取 gn 之后的数字。请注意,gn 元素可能在 gn 之前包含一些其他字符,并且在 gn@ 之后需要数字

def f(mess):
    p1 = mess.find('yl')
    p2 = mess.find('rd')
    b = mess[p1+3:].split(' ')[0]
    c = mess[p2+3:].split(' ')[0]
    return int(b),int(c)
id['vals'] = id['Message'].apply(f) #with this im able to get the numbers from yl and rd

标签: pythonregex

解决方案


让我们逐步解决这个问题。

  1. 只获取您感兴趣的行。
  2. 删除可能对我们没有用的数据。
  3. 使用剩下的数据来提取信息。

假设我将输入存储在一个变量中data,并且我需要将输出存储在一个名为final. 以下是我将如何解决这个问题。

useful = data.split('\n')[1:]  ## Step 1
code = [x[1].strip() for x in useful.split(',')] ## Step 2
gn_value = -1
yl_value = -1
rd_value = -1
for line in code:
    for each in line.split(' '): ## Step 3
        if 'gn@' in each:
            gn_value = int(each[each.find('gn@')+3:])
        elif 'yl@' in each:
            yl_value = int(each[each.find('yl@')+3:])
        elif 'rd@' in each:
            rd_value = int(each[each.find('rd@')+3:])
    final.append(gn_value, yl_value, rd_value)

注意:上述解决方案是在假设任何给定行中没有多次出现任何值的情况下开发的。

如果您有任何疑问,请告诉我。


推荐阅读