用Regex表达式提取从日期和到日期?

问题描述 投票:0回答:2

我想用Regex来提取从年和到年的数据,但由于格式不同,无法提取,如下图所示。([0-9]+)-?([0-9a-z]+)

以下是需要提取的完整数据。

['165-180 A.D.',
 '1520-unknown',
 '1665',
 '1817-1923',
 'Late 1800s',
 '1918-1920',
 '1957-1958',
 '2009']

上面的regex提取了165,1520。166 在第1组和2019年,未知。5 需要在第2组中把1665填入第1组,在第2组中的regex中填入空白字段。

wp_page = requests.get("https://www.washingtonpost.com/graphics/2020/local/retropolis/coronavirus-deadliest-pandemics/")
wp_soup = bs(wp_page.content, 'html.parser')

[names.get_text() for  names in wp_soup.find_all('h5')][0:-2]

wp_year_from_list=[]
wp_year_to_list=[]
wp_year_regex=re.compile('([0-9]+)-?([0-9a-z]+)')
for names in wp_soup.find_all('h5'):
    if (wp_year_regex.search(names.text)!= None):
        wp_year_from_list.append(wp_year_regex.search(names.text).group(1))
        wp_year_to_list.append(wp_year_regex.search(names.text).group(2))```
python python-3.x regex web-scraping list-comprehension
2个回答
2
投票

根据你的要求,你需要添加 ? 第二组的量化符。因此,你的regex将看起来像这样。

([0-9]+)-?([0-9a-z]+)?
                     ^^

上面的regex的解释:

([0-9]+) - 捕捉组:捕捉1次或多次的数字。

-? - 匹配一个连字符字面0或1次。

([0-9a-z]+)? - 第二个捕获组捕获数字和字母1次或多次,该组可以出现0次或1次。

enter image description here

你可以在下面的示例中找到上述的regex。这里。


1
投票

使用 * 在第二组中得到您所需的结果。

([0-9]+)-?([0-9a-z]+)*
                     ^^
© www.soinside.com 2019 - 2024. All rights reserved.