【问题标题】:How can I extract numbers from a string in Python, and return a list?如何从 Python 中的字符串中提取数字并返回一个列表?
【发布时间】:2020-12-23 13:26:02
【问题描述】:

我正在尝试查找文本中的所有数字并将它们返回到浮点数列表中。

在正文中:

  • 逗号用于分隔千位
  • 几个连续的数字用逗号和空格隔开
  • 数字可以附加到单词
text = "30feet is about 10metre but that's 1 rough estimate several numbers are like 2, 137, and 40 or something big numbers are like 2,137,040 or something"

我需要将输出作为浮点数列表返回,中间有逗号,但没有语音标记。

Eg. 
extract_numbers("1, 2, 3, un pasito pa'lante Maria")
    is [1.0, 2.0, 3.0]

不幸的是,我当前尝试的输出返回一个字符串:


def extract_numbers(text):
  nums = re.findall(r'\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)', text)
  
    return (("[{0}]".format( 
                       ', '.join(map(str, nums))))) 

extract_numbers(TEXT_SAMPLE)

如何返回列表中的数字?

【问题讨论】:

    标签: python python-3.x regex extract re


    【解决方案1】:

    您可以从匹配项中删除所有逗号,然后将结果映射到float

    你可以使用

    def extract_numbers(text):
      return [float(x.replace(',','')) for x in re.findall(r'\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)', text)]
    

    Python demo

    import re
     
    TEXT_SAMPLE = "30feet is about 10metre but that's 1 rough estimate several numbers are like 2, 137, and 40 or something big numbers are like 2,137,040 or something"
     
    def extract_numbers(text):
      return [float(x.replace(',','')) for x in re.findall(r'\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)', text)]
     
    print(extract_numbers(TEXT_SAMPLE))
    
    # => [30.0, 10.0, 1.0, 2.0, 137.0, 40.0, 2137040.0]
    

    【讨论】:

    • @Sundeep 对,我只是快速调整了 OP 代码,没有进一步收缩。
    【解决方案2】:

    这是一个业余代码,但我想它可以工作

      text = """30feet is about 10metre but that's 1 rough estimate several
      numbers are like 2, 137, and 40 or something big numbers are like 2,
      137,040 or something"""
      def extract_numbers(text):
        numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        _numbers = []
        a=0
        while(a<len(text)):
          i=text[a]
          if(i in numbers):
            number=""
            while(text[a] in numbers):
              number+=text[a]
              a+=1
            _numbers.append(number)
          else:
            a+=1
        float_numbers=list()
        for i in _numbers:
          float_numbers.append(float(i))
        return float_numbers
    print(extract_numbers(text))
    

    输出:[30.0, 10.0, 1.0, 2.0, 137.0, 40.0, 2.0, 137.0, 40.0]

    【讨论】:

      【解决方案3】:

      这应该以干净的方式解决问题。

      import re  
      def extract_numbers(txt):
          return [float(r.replace(',', '')) for r in re.findall(r'[\d,]+', txt)]
      

      它会首先查找并分组所有没有分隔的数字和逗号,然后它会返回数字。

      【讨论】:

      • 是的,这也适用于给定的样本.. 有一个规范列表,但我想不出这个解决方案会失败的案例
      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 2021-03-07
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 2020-09-20
      相关资源
      最近更新 更多