我有数据如下所示:
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
最佳答案
让我们逐步解决这个问题。
- 仅获取您感兴趣的线路。
- 删除可能对我们无用的数据。
- 使用剩下的数据来提取信息。
假设我将输入存储在变量 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)
注意:上述解决方案是在假设任何给定行中任何值都不会多次出现的情况下开发的。
如果您有任何疑问,请告诉我。
关于python - 用python从不规则值中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53829762/