Python - 从文件中删除数字并对它们求和

标签 python url beautifulsoup numbers

我最近开始学习Python。现在我想从网站上删除数字来总结它们。

这是我的代码:

# read data -> extract numbers -> compute sum
import urllib.request, urllib.parse
from bs4 import BeautifulSoup

html = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.html')
file = BeautifulSoup(html, 'html.parser')
tags = file('span')
calcs = 0
for tag in tags:
    tag.decode()
    calcs += int(tag.string)
print(calcs)

在第 11 行(calcs += ...)我不知道该怎么做,在互联网的某个地方我找到了 .string,它帮助我从行中获取数字,但我不太确定为什么它有效或者 .string 做了什么。我自己找不到任何相关信息来源。如果我将 .string 更改为 .int 它会得到“None”

我希望有人能给我解释一下 .string 的用法。

提前谢谢您。

最佳答案

您必须将 tag.string 转换为 int

tags = file('span')
calcs = sum([int(tag.string)  for tag in tags])

关于Python - 从文件中删除数字并对它们求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480109/

相关文章:

python - 使用还包含科学数字格式的 python 将逗号转换为 txt 中的点

url - url 变量中的斜杠

python-3.x - 使用 BeautifulSoup 提取标题

python - 使用 Colab 访问 "Shared with me"

python - 如果用户没有按下任何键,如何自动播放播放列表中的下一首歌曲?

python - 如何检查 DataFrame 是否为空?

python - Beautifulsoup 未返回页面的完整 html

php - Rest Api 的服务器端实现

java - 下载缩略图而不是整个图像

javascript - Python 从 PGA 网站上的 JavaScript 表中抓取