AttributeError:'元组'对象没有属性' items'

时间:2017-03-02 11:21:43

标签: list python-3.x

import re, time, _thread
import urllib.request
from bs4 import BeautifulSoup


def get_data(n):
    global s,r
    html=urllib.request.urlopen('http://www.fmkorea.com/index.php?mid=best&listStyle=webzine&page='+str(n))
    soup=BeautifulSoup(html,'lxml')
    l=soup.findAll('h3', {'class':'title'}) 

    for i in l:
        for j in re.split(r'''\)|\(|\'|\"|\?|\]|\[|,|\.|\ |\:''',i.text[:i.text.rfind('[')].strip()):
            s[j.strip()] = s.get(j.strip(),0) + 1
            r=r+1

    s={}
    r=0

    for _ in range(1,2037):
            _thread.start_new_thread(get_data, (_,))
            time.sleep(0.05)

        while r!=2036:
            time.sleep(3)

    with open('res','w') as f:
        s=sorted(s.items(),key=lambda x: x[1],reverse=True)
        for i in s:
            f.writelines(str(i[0]) + " : " + str(i[1])+"\n")
AttributeError                            Traceback (most recent call last)
<ipython-input-24-3e6cc449e797> in <module>()
     35 # 
     36 with open('res','w') as f:
---> 37     s=sorted(s.items(),key=lambda x: x[1],reverse=True)
     38     for i in s:
     39         f.writelines(str(i[0]) + " : " + str(i[1])+"\n")

AttributeError: 'list' object has no attribute 'items'

我不断为上面的代码收到此错误,似乎无法修复它。如何阻止AttributeError被提升?

1 个答案:

答案 0 :(得分:0)

项目适用于您无法在列表中使用的词典

>>> d = {1:'a'}
>>> d.items()
dict_items([(1, 'a')])

>>> l = [1,2]
>>> l.items()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'items'