【问题标题】:Python Regex: obtaining currency numbers from a stringPython Regex:从字符串中获取货币数字
【发布时间】:2017-12-27 18:45:47
【问题描述】:

我是 regex 的新手,我正在尝试使用 re.findall 从以下形式的字符串中提取类似货币的数字(整数或浮点数为 1 或 2dp):

'1000 - 2000' , '1000 -', '1000.4'

我一直在努力寻找一种正则表达式模式,该模式允许我将字符串中的所有数字提取到一个单独的列表中,希望能在此问题上提供任何帮助。

例如,

import re

pattern = '^\d*[.,]?\d*$'
temp = ['1000.5 - 2000.55']
strings = re.findall('^\d*[.,]?\d*$', temp[0])

我得到的输出是一个空列表,[]

我想获得

strings = ['1000.5','2000.55']

然后想将它们转换为浮点数

nums = [float(i) for i in strings]

【问题讨论】:

  • 你能提供样本输入和预期输出吗?否则,您的问题将被视为过于宽泛
  • 你也想要带 1 个小数点的浮点数吗?
  • 另外,当你说with 2dp 时,你的意思是如果你有一个像1.123 这样的数字,你想得到1.12,或者你想完全忽略它,以至于你没有它出现在输出中?另外,如果您有1.126,假设您想要截断最后一位数字以便得到1.12:您想要1.12 还是1.13 的四舍五入值?
  • 对这个问题的结构不佳表示歉意。我想考虑 1 dp 的数字,但想完全忽略超过 2 dp 的数字。这样就不会从字符串中提取像 1.126 这样的数字。

标签: python regex


【解决方案1】:

你可以试试这个:

import re
temp = ['1000.5 - 2000.55']
final_data = map(float, re.findall('\d+\.\d+|\d+', temp[0]))

输出:

[1000.5, 2000.55]

【讨论】:

    【解决方案2】:
    import re
    
    temp = ['1000.5 - 2000.55']
    strings = re.findall('\d+(?:[.,]\d*)?', temp[0])
    nums = [float(i) for i in strings]
    print(nums) # [1000.5, 2000.55]
    

    demo

    【讨论】:

      【解决方案3】:

      你可以使用[0-9.]+

      import re
      pattern=r'[0-9.]+'
      temp = ['1000.5 - 2000.55']
      for i in temp:
          print(list(map(lambda x:float(x),re.findall(pattern,i))))
      

      输出:

      [1000.5, 2000.55]
      

      你也可以一行完成:

      print([list(map(lambda x:float(x),re.findall(pattern,i))) for i in temp][0])
      

      输出:

      [1000.5, 2000.55]
      

      【讨论】:

        猜你喜欢
        • 2019-09-08
        • 2012-11-11
        • 1970-01-01
        • 2018-08-30
        • 1970-01-01
        • 2023-01-07
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        相关资源
        最近更新 更多