【问题标题】:python regex - extracting digits from string with numbers and characterspython regex - 从带有数字和字符的字符串中提取数字
【发布时间】:2020-01-21 03:53:59
【问题描述】:

我的数据包含诸如“ms2p5”、“ms3”、“ms10”之类的字符串,我需要将其提取为转换为数字的数字,如下所示。

'ms2p5' => 2.5
'ms3' => 3
'ms10' => 10

我尝试了下面的正则表达式,它能够得到匹配。一个问题是在提取的字符串中间有一个字符的值,如“2p5”。拥有一个能够很好地处理所有这些情况同时将它们转换为数值的通用函数的正确方法是什么?

import re
re.search(r'\d+[p]*\d*', str).group() 

【问题讨论】:

  • 你目前的正则表达式有什么问题?
  • ".".join(re.findall(r'\d+', string)) 呢?

标签: python regex


【解决方案1】:

str.joinre.findall 一起使用:

los = ['ms2p5', 'ms3', 'ms10']
print([float('.'.join(re.findall('\d+', i))) for i in los])

输出:

[2.5, 3.0, 10.0]

【讨论】:

    【解决方案2】:

    您可以编写一个提取函数来搜索一个数值(带或不带 p 的小数点,将 p 替换为 .,然后转换为浮点数。例如:

    import re
    
    def extract_num(s):
        return float(re.search(r'\d+p?\d*', s).group().replace('p', '.'))
    
    strs = ['ms2p5', 'ms3', 'ms10']
    print([extract_num(s) for s in strs])
    

    输出:

    [2.5, 3.0, 10.0]
    

    【讨论】:

      【解决方案3】:

      如果字符串都遵循您提供的示例,我可能会这样做:

      x = 'ms2p5'
      float(x[2:].replace('p', '.'))
      

      【讨论】:

        猜你喜欢
        • 2020-06-10
        • 2023-01-07
        • 1970-01-01
        • 2014-06-24
        • 1970-01-01
        • 2017-07-30
        • 2012-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多