我無法將鏈接的HTML文件中的數字相加(將它們相加)。添加HTML文件中提取的整數時遇到問題
我收到目前此錯誤:
Line 26 b=sum(y) typeError unsupported operand types for +: int and str
這裏是我的代碼
import urllib
from BeautifulSoup import *
import re
counter = 0
added = 0
url = "http://python-data.dr-chuck.net/comments_42.html"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the span tags
spans = soup('span')
for comments in spans:
print comments
counter +=1
#y = re.findall('(\d+)', comments) -- didnt work
#print y
#added += y
y = re.findall('(\d+)', str(soup))
print y
b = sum(y)
print b
print "Count", counter
print "Sum", added
我期望的輸出是一樣的東西:
Count: 50
Sum: 2482
正如你可以看到我註釋掉了我的代碼 - 我試圖像t一樣添加它們他原來。不知道爲什麼這不起作用。
#y = re.findall('(\d+)', comments) -- didnt work
#print y
#added += y
我也不知道爲什麼,這地方找到的號碼列表
y = re.findall('(\d+)', str(soup))
你正在總結字符串。嘗試用'b = sum(map(int,y))' – Pynchia
那麼,怎麼了?你有錯誤嗎?並且'b = sum(y)'工作嗎? –
@zetysz:我知道,但是OP會在'b = sum(y)'處得到一個錯誤。但OP只說他在評論部分發生錯誤。 –