python - 访问以下布局中的属性时出现“列表索引超出范围”错误
问题描述
我正在使用 twitter 流 API,但我无法访问该screen_name
属性,因为嵌套的各个层让我有点困惑
这是我尝试过的
results = t.search(q='tuberculosis', count=50)
all_tweets = results['statuses']
for tweet in all_tweets:
tweetString = tweet["text"]
name = tweet["entities"]["user_mentions"][0]["screen_name"]
time = tweet["created_at"]
df1['Tweet'] = [tweetString]
df1['Name'] = [name]
df1['Time'] = [time]
df = df.append(df1)
这是 JSON 布局:
[
{
"created_at": "Thu Apr 06 15:28:43 +0000 2017",
"id": 850007368138018817,
"id_str": "850007368138018817",
"text": "RT @TwitterDev: 1/ Today we’re sharing our vision for the future of the Twitter API platform!nalink",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "TwitterDev", <------ I want to access this
"name": "TwitterDev",
"id": 2244994945,
"id_str": "2244994945",
"indices": [
3,
14
]
}
],
"urls": [
{
"url": "Link",
"expanded_url": "https://cards.twitter.com/cards/18ce53wgo4h/3xo1c",
"display_url": "cards.twitter.com/cards/18ce53wg…",
"indices": [
94,
117
]
}
]
},
"source": "<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 6253282,
"id_str": "6253282",
"name": "Twitter API",
"screen_name": "twitterapi",
"location": "San Francisco, CA",
"description": "The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.",
"url": "Link",
"entities": {
"url": {
"urls": [
{
"url": "Link",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,......
解决方案
userMentions 列表可能为空,因此访问第 0 个索引值可能会给您此错误。
我已经修改了你的代码。我不确定您在哪里声明了 df1 和 df 之类的变量...但是,请参考我的更改
results = t.search(q='tuberculosis', count=50)
all_tweets = results['statuses']
for tweet in all_tweets:
tweetString = tweet["text"]
#name = tweet["entities"]["user_mentions"][0]["screen_name"]
userMentionList = tweet["entities"]["user_mentions"]
if len(userMentionList)>0:
for eachUserMention in userMentionList:
name = eachUserMention["screen_name"]
time = tweet["created_at"]
df1['Tweet'] = [tweetString]
df1['Name'] = [name]
df1['Time'] = [time]
df = df.append(df1)
推荐阅读
- c# - TDD - 在哪里检查文本文件格式是否正确?
- python - 使用针对另一列的 if 语句在 pandas 数据框中创建新列
- kotlin - Ktor HttpClient JsonFeature 可以使用 kotlinx.serialization
- python - 参数 -m/--mode 是必需的
- rest - 我的应用程序如何通过 Webhooks 通知?我是否需要轮询收件人 URL?
- excel - Excel VBA 宏在隐藏的工作表上运行
- c++ - 生成 boost::hana::set 的常量表达式问题
- javascript - 粘性导航栏 UI
- r - group_by() 并取自上次购买特定品牌以来的周数之间的差异
- flutter - Flutter 控制台 Windows 批处理文件未打开