如何在Twython中修复“AttributeError:'dict'对象没有属性'append'”

时间:2018-01-13 21:13:43

标签: python twython

我正在努力学习一些python,我想编写一个脚本,从我的twitter中提取我的关注者用户名并将其保存到文件中。

该脚本来自本网站https://www.silkstream.net/blog/2014/06/playing-with-followers-with-twython-csv.html

我输入的代码低于

from twython import Twython
import datetime

app_key = ""
app_secret = ""
oauth_token = ""
oauth_token_secret = ""

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
#twitter.update_status(status = "Testing a script dont mind this tweet")

followers = []
datestamp = datetime.datetime.now().strftime("%Y-%m-%d")
username = input("what is your username: ")
next_cursor = -1
while(next_cursor):
    get_followers = twitter.get_followers_list(screen_name=username,count=200,cursor=next_cursor)
    for followers in get_followers["users"]:
        followers.append(follower["screen_name"].encode("utf-8"))
        next_cursor = get_followers["next_cursor"]

followers_text = open(username+"-"+datestamp+".txt","a")
followers_text.write("%s has %s followers (%s)):" % (str(username),str(len(followers)),str(datestamp))+"".join(followers))
followers_text.close()

当我运行程序时,我得到了这个输出

File "first.py", line 19, in <module>
followers.append(follower["screen_name"].encode("utf-8"))
AttributeError: 'dict' object has no attribute 'append'

如果我注释掉第19行它实际上会运行,但我在保存的文件中得到了这个奇怪的输出

idid_strnamescreen_namelocationdescriptionurlentitiesprotectedfollowers_countfriends_countlisted_countcreated_atfavourites_countutc_offsettime_zonegeo_enabledverifiedstatuses_countlangstatuscontributors_enabledis_translatoris_translation_enabledprofile_background_colorprofile_background_image_urlprofile_background_image_url_httpsprofile_background_tileprofile_image_urlprofile_image_url_httpsprofile_banner_urlprofile_link_colorprofile_sidebar_border_colorprofile_sidebar_fill_colorprofile_text_colorprofile_use_background_imagehas_extended_profiledefault_profiledefault_profile_imagefollowinglive_followingfollow_request_sentnotificationsmutingblockingblocked_bytranslator_type

看起来它认为某些东西是字典(或者至少是我的猜测),但我没有在那里做过吗?

1 个答案:

答案 0 :(得分:1)

您使用名称followers作为变量名称两次,您应该使用两个不同的名称:

followers = []
# ...
    for followers in get_followers["users"]: