python - 用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
解决方案
让我们逐步解决这个问题。
- 只获取您感兴趣的行。
- 删除可能对我们没有用的数据。
- 使用剩下的数据来提取信息。
假设我将输入存储在一个变量中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)
注意:上述解决方案是在假设任何给定行中没有多次出现任何值的情况下开发的。
如果您有任何疑问,请告诉我。
推荐阅读
- rest - 路由的 REST API 最佳实践
- r - ggplot2 将数据框的每一列与其他每一列进行对比
- javascript - 可以在 webcomponent 内部使用 vuejs 吗?
- javascript - 渲染将在 React 组件中实际运行多少次
- php - 如果列为空,则在 php 中回显出错
- ios - 跟踪用户喜欢的帖子 - flutter 和 firestore
- rundeck - 项目名称目录未在 rundeck 中创建
- apache-flink - 具有两个接收器的两阶段提交协议
- unit-testing - 使用 Jest 在 Nuxt 中测试组件时如何添加/模拟 Nuxt Auth 库
- android - 如何在 Windows 中通过颤振测试 ios 应用程序