python字符串以更健壮的方式解析数字

2024-09-30 14:19:51 发布

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

抓取一个网站后得到一个字符串

 '<p class="NewsItemContent" style="font-size: 18px;">;As of March 18, 1999, 
6 p.m. Pacific Daylight Time, there are a total of 70;events and 16;planned  
in this area. This total does not include adjacent cities.</p>'

我怎么能解析出70,16。 只是想要一种更健壮的方式。措辞可能会有一点变化,但总是总共{};事件和{};计划。 谢谢


Tags: of字符串sizetime网站styleasclass
1条回答
网友
1楼 · 发布于 2024-09-30 14:19:51

这不是一个非常干净的解决方案,但我们现在开始:

import re

s = ('<p class="NewsItemContent" style="font-size: 18px;">;As of March 18, 1999, '
     '6 p.m. Pacific Daylight Time, there are a total of 70;events and 16;planned  '
     'in this area. This total does not include adjacent cities.</p>')

s = s.split('a total of ')[1]  # split by 'a total of' to get the second part

print(re.findall('\d+', s)[:2])  # finding the first two digits
['70', '16']

相关问题 更多 >