我最近开始学习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/