类型错误:';int';对象不可订阅-python
我正在尝试制作一个小程序,它会随机生成一个网站,并统计元素 这是我的错误:类型错误:';int';对象不可订阅-python,python,list,int,typeerror,Python,List,Int,Typeerror,我正在尝试制作一个小程序,它会随机生成一个网站,并统计元素 这是我的错误: Traceback (most recent call last): File "elements counter.py", line 23, in <module> if elem[1] == string: TypeError: 'int' object is unsubscriptable 回溯(最近一次呼叫最后一次): 文件“elements counter.py”,第23行,在 如果元
Traceback (most recent call last):
File "elements counter.py", line 23, in <module>
if elem[1] == string:
TypeError: 'int' object is unsubscriptable
回溯(最近一次呼叫最后一次):
文件“elements counter.py”,第23行,在
如果元素[1]==字符串:
TypeError:“int”对象不可订阅
这是我的密码:
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()
来自urllib2导入请求、urlopen、URLError
打印“获取URL…”
尝试:
html=urlopen(请求(“http://www.randomwebsite.com/cgi-bin/random.pl"))
除URL错误外:
html=urlopen(请求(“http://www.randomwebsitemachine.com/random_website/"))
打印“正在加载HTML…”
ellist=[(无,无),]
isel=假
字符串=“”
对于html.read()中的字符:
如果char='':
如果字符串在椭圆列表中:
对于ellist中的elem:
如果元素[1]==字符串:
元素[0]+=1
其他:
ellist+=(1,字符串)
isel=假
字符串=“”
其他:
字符串+=字符
打印排序(ellist,key=lambda tempvar:tempvar[0])
html.close()
原始输入()
如果您在代码中发现任何错误,请指出。当您发现错误时
ellist += (1,string)
这和
ellist.extend((1,string))
因此,ellist
看起来像
[(None, None), 1, string]
因此,当您到达for
循环中的第二个元素时,它是int
而不是tuple
相反,你应该这样做
ellist.append((1,string))
或者,如果您确实想使用+=
ellist += [(1,string)]
代码的其余部分看起来基本正确,但请注意,您无法正确处理引号或HTML注释中的尖括号。如果您想解析HTML,请使用许多HTML解析器中的一个,如Python的HTMLParser模块、lxml或BeautifulSoup。您不应该命名变量
string
,它可能与string
冲突module@AnuragUniyal通常使用模块名作为标识符,只要你没有在程序中使用该模块。有太多的人需要担心。惯例是避免使用常用的内置标识符,如list
或dict
。较不常用的名称,如file
或id
,取决于您询问的人——它们通常在标准库中使用。@agf是的,但通常最好避免与std lib模块冲突或描述不够,字符串最好按照应该的名称命名,例如search_str或tag_name等