首页 文章

Python:从字符串中提取数字

提问于
浏览
302

我会提取字符串中包含的所有数字 . 哪个更适合用于目的,正则表达式或 isdigit() 方法?

例:

line = "hello 12 hi 89"

结果:

[12, 89]

13 回答

  • 337

    如果您只想提取正整数,请尝试以下操作:

    >>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
    >>> [int(s) for s in str.split() if s.isdigit()]
    [23, 11, 2]
    

    我认为这比正则表达式的例子好三个原因 . 首先,你不需要另一个模块;其次,它更具可读性,因为你不需要解析正则表达式迷你语言;第三,它更快(因此可能更加pythonic):

    python -m timeit -s "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "[s for s in str.split() if s.isdigit()]"
    100 loops, best of 3: 2.84 msec per loop
    
    python -m timeit -s "import re" "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "re.findall('\\b\\d+\\b', str)"
    100 loops, best of 3: 5.66 msec per loop
    

    这将无法识别十六进制格式的浮点数,负整数或整数 . 如果你不能接受这些限制,那么slim's answer below就可以了 .

  • 0

    我使用正则表达式:

    >>> import re
    >>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
    ['42', '32', '30']
    

    这也将与 bla42bla 匹配42 . 如果您只想要按字边界(空格,句号,逗号)分隔的数字,则可以使用\ b:

    >>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
    ['42', '32', '30']
    

    最终得到一个数字列表而不是字符串列表:

    >>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
    [42, 32, 30]
    
  • 5

    这有点晚了,但您可以扩展正则表达式以考虑科学记数法 .

    import re
    
    # Format is [(<string>, <expected output>), ...]
    ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
           ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
          ('hello X42 I\'m a Y-32.35 string Z30',
           ['42', '-32.35', '30']),
          ('he33llo 42 I\'m a 32 string -30', 
           ['33', '42', '32', '-30']),
          ('h3110 23 cat 444.4 rabbit 11 2 dog', 
           ['3110', '23', '444.4', '11', '2']),
          ('hello 12 hi 89', 
           ['12', '89']),
          ('4', 
           ['4']),
          ('I like 74,600 commas not,500', 
           ['74,600', '500']),
          ('I like bad math 1+2=.001', 
           ['1', '+2', '.001'])]
    
    for s, r in ss:
        rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
        if rr == r:
            print('GOOD')
        else:
            print('WRONG', rr, 'should be', r)
    

    给所有人带来好处!

    另外,你可以看一下AWS Glue built-in regex

  • 4

    我假设你想要浮点数不仅仅是整数,所以我会做这样的事情:

    l = []
    for t in s.split():
        try:
            l.append(float(t))
        except ValueError:
            pass
    

    请注意,此处发布的其他一些解决方案不适用于负数:

    >>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string -30')
    ['42', '32', '30']
    
    >>> '-3'.isdigit()
    False
    
  • 74

    如果您知道字符串中只有一个数字,即'hello 12 hi',您可以尝试过滤 .

    例如:

    In [1]: int(filter(str.isdigit, '200 grams'))
    Out[1]: 200
    In [2]: int(filter(str.isdigit, 'Counters: 55'))
    Out[2]: 55
    In [3]: int(filter(str.isdigit, 'more than 23 times'))
    Out[3]: 23
    

    但要小心!!! :

    In [4]: int(filter(str.isdigit, '200 grams 5'))
    Out[4]: 2005
    
  • 1

    这个答案还包含数字在字符串中浮动的情况

    def get_first_nbr_from_str(input_str):
        '''
        :param input_str: strings that contains digit and words
        :return: the number extracted from the input_str
        demo:
        'ab324.23.123xyz': 324.23
        '.5abc44': 0.5
        '''
        if not input_str and not isinstance(input_str, str):
            return 0
        out_number = ''
        for ele in input_str:
            if (ele == '.' and '.' not in out_number) or ele.isdigit():
                out_number += ele
            elif out_number:
                break
        return float(out_number)
    
  • 41
    # extract numbers from garbage string:
    s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
    newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
    listOfNumbers = [float(i) for i in newstr.split()]
    print(listOfNumbers)
    [12.0, 3.14, 0.0, 1.6e-19, 334.0]
    
  • 59

    令我惊讶的是,没有人提到使用itertools.groupby作为实现这一目标的替代方案 .

    您可以将itertools.groupby()str.isdigit()一起使用,以便从字符串中提取数字:

    from itertools import groupby
    my_str = "hello 12 hi 89"
    
    l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]
    

    l 保持的值为:

    [12, 89]
    

    PS: 这只是为了说明目的,以表明作为替代方案,我们也可以使用 groupby 来实现这一目标 . 但这不是推荐的解决方案 . 如果你想实现这个,你应该使用accepted answer of fmark基于使用列表理解和 str.isdigit 作为过滤器 .

  • 2

    我一直在寻找一种解决方案,以删除字符串的面具,特别是从巴西手机号码,这篇文章没有回答,但启发了我 . 这是我的解决方案:

    >>> phone_number = '+55(11)8715-9877'
    >>> ''.join([n for n in phone_number if n.isdigit()])
    '551187159877'
    
  • 7

    由于这些都不涉及我需要找到的excel和word文档中的真实世界金融数字,所以这是我的变体 . 它处理整数,浮点数,负数,货币数(因为它不会在拆分时回复),并且可以选择删除小数部分并返回整数,或者返回所有内容 .

    它还处理印度拉克斯数字系统,其中逗号不规则地出现,而不是每隔3个数字 .

    它不处理科学记数法或在预算中括号内的负数 - 将显得积极 .

    它也不提取日期 . 有更好的方法可以在字符串中查找日期 .

    import re
    def find_numbers(string, ints=True):            
        numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
        numbers = numexp.findall(string)    
        numbers = [x.replace(',','') for x in numbers]
        if ints is True:
            return [int(x.replace(',','').split('.')[0]) for x in numbers]            
        else:
            return numbers
    
  • 0

    @jmnas,我很喜欢你的答案,但它没有't find floats. I'正在编写一个脚本来解析进入CNC铣床的代码,并且需要找到可以是整数或浮点数的X和Y维度,所以我将你的代码改编成以下内容 . 这找到了int,float,带有正负val . 仍然没有找到十六进制格式的值,但你可以通过 num_char _元组添加"x"和"A",我认为它会解析像'0x23AC'这样的东西 .

    s = 'hello X42 I\'m a Y-32.35 string Z30'
    xy = ("X", "Y")
    num_char = (".", "+", "-")
    
    l = []
    
    tokens = s.split()
    for token in tokens:
    
        if token.startswith(xy):
            num = ""
            for char in token:
                # print(char)
                if char.isdigit() or (char in num_char):
                    num = num + char
    
            try:
                l.append(float(num))
            except ValueError:
                pass
    
    print(l)
    
  • 332

    我找到的最佳选择如下 . 它将提取一个数字并可以消除任何类型的char .

    def extract_nbr(input_str):
        if input_str is None or input_str == '':
            return 0
    
        out_number = ''
        for ele in input_str:
            if ele.isdigit():
                out_number += ele
        return float(out_number)
    
  • 6

    下面使用正则表达式

    lines = "hello 12 hi 89"
    import re
    output = []
    line = lines.split()
    for word in line:
            match = re.search(r'\d+.?\d*', word)
            if match:
                output.append(float(match.group()))
    print (output)
    

相关问题