【问题标题】:Python - strip numbers from file and sum them upPython - 从文件中删除数字并将它们总结起来
【发布时间】:2018-07-23 13:33:37
【问题描述】:

我最近开始学习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的用法。

提前致谢。

【问题讨论】:

标签: python url beautifulsoup numbers


【解决方案1】:

您必须将tag.string 转换为int

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

【讨论】:

    【解决方案2】:

    .stringTag 对象的成员变量。没有.int 成员,这就是为什么您在尝试访问该值时会得到None

    您的calcs=... 行中发生的情况是,您从标签中获取数据为str,然后将str 转换为int,这似乎是一种完全有效的方式获取您的号码列表。

    【讨论】:

    • 非常感谢,帮了大忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2012-04-12
    • 2021-05-18
    • 2017-03-08
    • 2021-05-30
    • 2010-10-19
    相关资源
    最近更新 更多