2012-04-05 107 views
0

我正在嘗試製作一個小程序,它可以獲取一個隨機網站並計算元素。TypeError:'int'object is unsubscriptable - python

這是我的錯誤:

Traceback (most recent call last): 
    File "elements counter.py", line 23, in <module> 
    if elem[1] == string: 
TypeError: 'int' object is unsubscriptable 

這裏是我的代碼:

from urllib2 import Request, urlopen, URLError 

print 'Fetching URL..' 

try: 
    html = urlopen(Request("http://www.randomwebsite.com/cgi-bin/random.pl")) 
except URLError: 
    html = urlopen(Request("http://www.randomwebsitemachine.com/random_website/")) 

print 'Loading HTML..' 

ellist = [(None,None),] 
isel = False 
string = '' 

for char in html.read(): 
    if char == '<': 
     isel=True 
    elif isel: 
     if char == ' ' or char == '>': 
      if string in ellist: 
       for elem in ellist: 
        if elem[1] == string: 
         elem[0] += 1 
      else: 
       ellist += (1,string) 
      isel = False 
      string = '' 
     else: 
      string += char 

print sorted(ellist, key = lambda tempvar: tempvar[0]) 

html.close() 
raw_input() 

請指出,如果你發現任何錯誤多的代碼。

+1

你不應該命名你的變量'string',它可能與'string'模塊衝突 – 2012-04-05 15:57:02

+0

@AuuragUniyal只要你沒有在你的程序中使用模塊,通常使用模塊名作爲標識符。有太多需要擔心的事情。該慣例是爲了避免使用常用的內置函數作爲標識符,比如'list'或'dict'。較少使用的文件如'file'或'id'取決於你問的對象 - 它們通常在標準庫中使用。 – agf 2012-04-05 15:59:40

+0

@agf是的,但通常避免與std lib模塊衝突的名稱或描述性不夠好的字符串會更好,字符串會更好地命名爲例如應該是例如。 search_str或tag_name等 – 2012-04-05 16:02:55

回答

2

當你做的

  ellist += (1,string) 

它一樣

  ellist.extend((1,string)) 

所以ellist看起來像

[(None, None), 1, string] 

所以當你得到第二個元素在for循環,它不是tuple

相反,做

  ellist.append((1,string)) 

或者,如果你真的想用+=

  ellist += [(1,string)] 

你的代碼的其餘部分看起來基本上是正確的,但要注意你將不能正確處理尖括號在引號或HTML註釋中。如果要解析HTML,請使用其中的一個HTML解析器,如Python的HTMLParser模塊,lxml或BeautifulSoup。