Python:从字符串中提取数字

pab*_*che 388 python regex string numbers

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

例:

line = "hello 12 hi 89"
Run Code Online (Sandbox Code Playgroud)

结果:

[12, 89]
Run Code Online (Sandbox Code Playgroud)

fma*_*ark 430

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

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

我认为这比正则表达式的例子好三个原因.首先,你不需要另一个模块; 其次,它更具可读性,因为你不需要解析正则表达式迷你语言; 第三,它更快(因此可能更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
Run Code Online (Sandbox Code Playgroud)

这将无法识别十六进制格式的浮点数,负整数或整数.如果你不能接受这些限制,下面的苗条答案将起到作用.

  • 我有像"mumblejumble45mumblejumble"这样的字符串,其中我知道只有一个数字.解决方案只是``int(filter(str.isdigit,your_string))``. (16认同)
  • 清除程序:`[s(s)for s in str.split()if s.isdigit()]`==>`[23,11,2]` (11认同)
  • `int(filter(...))`会引发`TypeError:int()参数必须是一个字符串...`for Python 3.5,所以你可以使用更新版本:`int(''.join(filter(str) .isdigit,your_string)))`用于将所有数字提取到一个整数. (10认同)
  • 规范案例是使用`re`.它是一个通用且强大的工具(所以你学到了非常有用的东西).速度在日志解析中有点无关紧要(毕竟它不是一些强大的数值求解器),`re`模块在标准的Python库中,加载它并没有什么坏处. (8认同)
  • 对于像"h3110 23 cat 444.4 rabbit 11-2 dog"这样的情况,这将失败 (5认同)
  • 一个小评论:您定义了变量 ``str``,然后它会覆盖基础 Python 中的 ``str`` 对象和方法。这不是一个好习惯,因为您可能在脚本的后面需要它。 (2认同)

Vin*_*ard 404

我使用正则表达式:

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

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

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

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

>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
[42, 32, 30]
Run Code Online (Sandbox Code Playgroud)

  • ...然后将`int`映射到它上面就完成了.+1尤其适用于后者.我建议使用原始字符串(`r'\ b\d +\b'=='\\ b \\ d + \\ b'`). (9认同)
  • @GreenMatt:这在技术上是一个列表理解(不是生成器),但我同意理解/生成器比`map`更像Pythonic. (7认同)
  • 它可以放在带有生成器的列表中,例如:`int_list = [int(s)for s in re.findall('\\ d +','hello 12 hi 89')]` (5认同)
  • 这对于非整数不起作用 `>>>temp='temp=46.7 Degrees` `>>>re.findall(r'\d+',temp)` 给出 `['46','7']` 。对于这种特殊情况,请使用 `re.findall(r'\d+\.\d+',temp)` 。 (3认同)
  • 我有一个问题。如果我想在“hello1.45 hi”中提取浮点数也像 1.45 怎么办。它会给我 1 和 45 作为两个不同的数字 (2认同)

aid*_*ald 81

这有点晚了,但你可以扩展正则表达式来解释科学记数法.

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)
Run Code Online (Sandbox Code Playgroud)

给所有人带来好处!

此外,您还可以查看AWS Glue内置正则表达式

  • 是啊,明显的`[ - +]?[.]?[\ d] +(?:,\ d\d\d)*[\.]?\ d*(?:[eE] [ - +] ?\ d +)?` - 我这么傻......我怎么能不这么想? (17认同)

jmn*_*nas 67

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

l = []
for t in s.split():
    try:
        l.append(float(t))
    except ValueError:
        pass
Run Code Online (Sandbox Code Playgroud)

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

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

>>> '-3'.isdigit()
False
Run Code Online (Sandbox Code Playgroud)

  • 对于负数:`re.findall("[ - \d] +","1 -2")` (3认同)

dfo*_*tic 58

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

例如:

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

但要小心!!! :

In [4]: int(''.join(filter(str.isdigit, '200 grams 5')))
Out[4]: 2005
Run Code Online (Sandbox Code Playgroud)

  • 在Python 3.6.3中我得到了`TypeError:int()参数必须是一个字符串,一个类似字节的对象或一个数字,而不是'filter'` - 使用`int("".join(filter(str.) isdigit,'200克')))` (11认同)

Jam*_*ush 21

为了捕捉不同的模式,使用不同的模式进行查询是有帮助的。

设置捕获不同数量感兴趣模式的所有模式:

(查找逗号)12,300 或 12,300.00

'[\d]+[.,\d]+'

(查找浮点数)0.123 或 .123

'[\d]*[.][\d]+'

(查找整数)123

'[\d]+'

与管道 (|) 组合成具有多个或条件的一种模式。

(注意:将复杂模式放在首位,否则简单模式将返回复杂捕获的块,而不是返回完整捕获的复杂捕获)。

p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
Run Code Online (Sandbox Code Playgroud)

下面,我们将使用 确认模式存在re.search(),然后返回一个可迭代的捕获列表。最后,我们将使用括号表示法打印每个捕获,以从匹配对象中子选择匹配对象返回值。

s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'

if re.search(p, s) is not None:
    for catch in re.finditer(p, s):
        print(catch[0]) # catch is a match object
Run Code Online (Sandbox Code Playgroud)

返回:

33
42
32
30
444.4
12,001
Run Code Online (Sandbox Code Playgroud)


Ant*_*REL 16

对于电话号码,您可以使用\D正则表达式简单地排除所有非数字字符:

import re

phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)
Run Code Online (Sandbox Code Playgroud)

rr"\D"代表原始字符串。有必要。没有它,Python 将视为\D转义字符。


小智 12

# 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]
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到 SO,感谢您发布答案。在您的答案中添加一些额外的评论以及为什么它可以解决问题始终是一个好习惯,而不仅仅是发布代码片段。 (3认同)

Sid*_*don 12

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

>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'
Run Code Online (Sandbox Code Playgroud)


Diw*_*RMA 9

line2 = "hello 12 hi 89"  # this is the given string 
temp1 = re.findall(r'\d+', line2) # find number of digits through regular expression
res2 = list(map(int, temp1))
print(res2)
Run Code Online (Sandbox Code Playgroud)

你好 ,

您可以使用 findall 表达式通过 digit 搜索字符串中的所有整数。

在第二步中创建一个列表 res2 并将字符串中找到的数字添加到此列表中

希望这可以帮助

问候, 迪瓦卡尔·夏尔马

  • 提供的答案被标记为低质量帖子以供审核。以下是[如何写出好的答案?](https://stackoverflow.com/help/how-to-answer) 的一些指南。这个提供的答案可能是正确的,但它可能会受益于解释。仅代码答案不被视为“好”答案。来自[评论](https://stackoverflow.com/review)。 (2认同)

Men*_* Li 7

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

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)
Run Code Online (Sandbox Code Playgroud)


sim*_*sim 6

在下面使用正则表达式是

lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
        match = re.search(repl_str, word)
        if match:
            output.append(float(match.group()))
print (output)
Run Code Online (Sandbox Code Playgroud)

与findall re.findall(r'\d+', "hello 12 hi 89")

['12', '89']
Run Code Online (Sandbox Code Playgroud)

re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")

 ['12', '89', '777']
Run Code Online (Sandbox Code Playgroud)

  • `repl_str = re.compile('\d+.?\d*')` 应该是: `repl_str = re.compile('\d+\.?\d*')` 对于使用 python3.7 的可重现示例 `re .search(re.compile(r'\d+.?\d*'), "42G").group()` '42G' `re.search(re.compile(r'\d+\.?\d* '), "42G").group()` '42' (2认同)

Rag*_*hav 6

我只是添加这个答案,因为没有人使用异常处理添加一个答案,因为这也适用于浮点数

a = []
line = "abcd 1234 efgh 56.78 ij"
for word in line.split():
    try:
        a.append(float(word))
    except ValueError:
        pass
print(a)
Run Code Online (Sandbox Code Playgroud)

输出 :

[1234.0, 56.78]
Run Code Online (Sandbox Code Playgroud)


Moi*_*dri 5

令我惊讶的是,没有人提到使用它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]
Run Code Online (Sandbox Code Playgroud)

持有的价值l将是:

[12, 89]
Run Code Online (Sandbox Code Playgroud)

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