python - 用python从不规则值中提取数字

标签 python regex

我有数据如下所示:

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

最佳答案

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

  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)

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

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

关于python - 用python从不规则值中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53829762/

相关文章:

python - 如何检测模型属性是否是外键关系? (并检索所有 FK 模型对象)

javascript - 在字符第一次出现时停止匹配,或继续

Python 正则表达式 : Proper way to extract separated numbers (AxBxC -> [A, B, C])

regex - 在 Unix 命令/脚本中查找该行的前 4 个字符应为 "ORA-",接下来的 5 个字符应为数字

c++ - 如何在 C++ 的正则表达式中使用变量?

python - 遍历类的字典时如何返回类值

python - 计算 32 位整数列表中的非零位

python - 隐藏 os.system 产生的控制台输出

python - 从网站中的警报中获取文本

regex - 如何使用正则表达式匹配特定域中的所有电子邮件地址?