【问题标题】:How to add up scraped strings representing integers?如何将表示整数的抓取字符串相加?
【发布时间】:2016-04-22 00:33:00
【问题描述】:

如何将我抓取的所有浮点数加起来?

for post in posts:
    numberOfItems = numberOfItems + 1
    print(numberOfItems)
    value = float(re.sub(r"[^\d.]", "", post.text))
    print("Chaos orbs: %s" % value)
    print(value)

像这样 print(value1 + value2 + value3) 但是,这将是一个我不知道的随机数量,所以我不能制作变量

【问题讨论】:

  • 你能举个post.text的例子吗?或者至少确认您计算的value 正在返回正确的结果?

标签: python python-2.7 python-3.x selenium


【解决方案1】:

使用sum():

for post in posts:
    ... # rest of code snippet you posted

print(sum(float(re.sub(r"[^\d.]", "", post.text)) for post in posts))

在您的 for 循环之外,会将所有值相加并打印出总和。


或者,如果您想以某种方式使用现有的 for 循环来避免迭代两次,那么:

summed_values = 0
for post in post:
    ... # rest of code snippet you posted
    summed_values += value

【讨论】:

  • 谢谢,知道我会如何划分吗?
  • @Nevermind123 划分什么?总和值?只需像通常对任何数字一样将总和值相除:summed_value/some_divisor。如果使用第一种方法,只需将sum 调用分开:sum(...)/some_divisor。如果您打算提出与您提出的问题的性质无关的后续问题,请将它们作为一个单独的问题提出 - 这样,更多的人可以帮助您,而不仅仅是我。:)
【解决方案2】:

你想实现这个吗:

post="1.0  2.0  3.0\n 1.5 2.3"
print sum(map(float,post.split()))

【讨论】:

    【解决方案3】:

    不清楚你在抓取什么,但这应该提取数值:

    import re
    
    s = "abc 12.25 def 20 df20.5 $10,000.50"
    
    >>> re.findall(r"([\d.?]+)", re.sub(",", "", s))
    ['12.25', '20', '20.5', '10000.50']
    

    此正则表达式从字符串中删除逗号,并将结果传递给另一个正则表达式,以查找所有可能有或没有小数的数字 (\d) (.?)。

    整数字符串列表很容易求和:

    >>> sum(float(n) for n in re.findall(r"([\d.?]+)", re.sub(",", "", s)))
    10053.25
    

    然后你在外循环中总计:

    total_sum = 0
    for post in posts:
        ...
        total_sum += sum(float(n) for n in re.findall(r"([\d.?]+)", re.sub(",", "", s)))
        ...
    

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      相关资源
      最近更新 更多