从字符串到int Python的高级解析

2024-09-29 03:31:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从维基百科. 我有字符串a='420000+文章',我需要得到intb=4200000。 我用BS4得到了这个字符串,并尝试用int(a)进行简单的解析,但是 显然这行不通。 你能帮帮我吗?在


Tags: 字符串文章intbs4帮帮我intb
3条回答

你需要一个正则表达式来从这样的文本中获取数字:

import re

int_numbers = re.compile('\d[\d ]*')

def extract_integer(text):
    value_match = int_numbers.search(text)
    if value_match:
        try:
            return int(value_match.group().replace(' ', ''))
        except ValueError:
            # failed to create an int, ignore
            pass

该模式匹配后跟0个或更多个数字或空格的数字。在

演示:

^{pr2}$

如果在输入文本中需要all这样的数字,请使用.finditer()和生成器:

def extract_integers(text):
    for value_match in int_numbers.finditer(text):
        try:
            yield int(value_match.group().replace(' ', ''))
        except ValueError:
            # failed to create an int, ignore
            pass

演示:

>>> for i in extract_integers('4 300 123 times 42'):
...     print i
...
4300123
42
>>> list(extract_integers('4 300 123 times 42'))
[4300123, 42]
>>> import re 
>>> a = re.findall(r'[\d ]+',  '4 200 000+ articles' )
>>> print a
['4 200 000', ' ']
>>> [x.replace(' ','') for x in a if x.strip()]
['4200000']

如果您只想删除除数字以外的所有内容,可以使用类似于:

>>> x = "500000+"
>>> import string
>>> all=string.maketrans('','')
>>> nodigs=all.translate(all, string.digits)
>>> x.translate(all, nodigs)

这将删除字符串中除数字0-9之外的所有字符。在

相关问题 更多 >