python - 如何在正则表达式中使用括号获得多个数字
问题描述
我试图在 python3 中使用 urllib 和正则表达式从 html 代码中提取值,当我尝试运行此代码时,它只给了我一个数字而不是两个值,即使我添加了一个“+”符号表示一次或多次。这里有什么问题?
import re
import urllib.error,urllib.parse,urllib.request
from bs4 import BeautifulSoup
finalnums=[]
sumn=0
urlfile = urllib.request.urlopen("http://py4e-data.dr-chuck.net/comments_42.html")
html=urlfile.read()
soup = BeautifulSoup( html,"html.parser" )
spantags = soup("span")
for span in spantags:
span=span.decode()
numlist=re.findall(".+([0-9].*)<",span)
print(numlist)
finalnums.extend(numlist)
for anum in finalnums:
sumn=sumn+int(anum)
print("Sum = ",sumn)
这是我试图从中提取数字的字符串示例:
<span class="comments">54</span>
解决方案
用于numlist=re.findall("\d+",span)
搜索所有连续的数字字符组。
\d
是一个相当于 的字符类[0-9]
,所以如果你这样做它也可以工作numlist=re.findall("[0-9]+",span)
推荐阅读
- javascript - 从服务器端点获取音频文件并在反应应用程序中播放
- python - 数据未传递给for循环中的变量
- java - Thymeleaf 到 madal jquery
- jenkins-pipeline - 使用 Puppeteer 捕获 ChromeHeadless 启动器的问题
- reactjs - 如何在不获取整个材料/核心的情况下仅使用 MUI-Datatable?
- r - predict.lm 计算的 90% 或 95% 置信区间
- html - a:visited for docx files -- 颜色在 IE 和 Chrome 中不会改变
- sql - 如何组合 2 个 SQL 查询
- node.js - 恢复为 nvm 默认版本
- c - 使用 C 代码中更新的编译器工具链摆脱“表达式必须是常量值”