TypeError:'int'对象在Python Twitter API上不可迭代

问题描述 投票:-1回答:1

我正在使用Twitter库从推文中提取text,screen_name,hashtags,follower count等。

获取screen_name,hashtags和text没有问题,因为它们都是字符串。

如何提取作为'int'对象的跟随者计数并保存为列表格式?

status_texts = [status['text']
                for status in statuses]
screen_names = [user_mention['screen_name']
                for status in statuses
                    for user_mention in status['entities']['user_mentions']]
followers = [user['followers_count']
            for status in statuses
                for user in status['user']['followers_count']]

前两个代码的结果是

["RT @ESPNStatsInfo: Seven of the NBA's top 10 all-time leading scorers never had back-to-back 50-point games. \n\nKareem Abdul-Jabbar\nKarl Mal…", 'RT @kirkgoldsberry: The game has changed. Rookie LeBron versus Doncic"]
['ESPNStatsInfo', 'kirkgoldsberry', 'ESPNStatsInfo', 'warriors', 'MT_Prxphet', 'Verzilix', 'BleacherReport']

我的预期结果是

[10930,13213,15322,8795,9328,23519]

但是当我尝试提取关注者的数量并将其保存为列表格式时,它会返回TypeError: 'int' object is not iterable。我知道我收到此错误,因为follower_counts的结果是整数,我不能使用整数的for

在这种情况下,我需要将int转换为str吗?还是我需要使用range

我知道使用tweepy更容易,但我想首先使用twitter

python for-loop twitter iterable
1个回答
0
投票

所以我希望代表你的API调用的json响应的字典被称为qazxsw poi。

通过这种方式,您已经知道通过执行jsonResponse可以获得每条推文。 (我期待你的statuses = jsonResponse['statuses']也是如此。)

从那里,我猜你想要每个推文的关注者数量列表。因此,对于状态中的状态,您希望关注者计数。在python中,它看起来像这样:

statuses

另一种方法是映射followers_counts = [status['user']['followers_count'] for status in statuses] 列表:

statuses

使用followers_count = map(lambda status: status['user']['followers_count'], statuses) ,你甚至可以更简单地为每条推文制作一份你想要的信息字典。但这看起来就像你已经从API获得的json。

© www.soinside.com 2019 - 2024. All rights reserved.