【问题标题】:Twitter: 'dict_keys' object does not support indexingTwitter:“dict_keys”对象不支持索引
【发布时间】:2017-12-28 03:05:40
【问题描述】:

我想用 python 分析 twitter 数据(JSON 文件),这里是脚本:

import json
fname = 'analisis.json' with open(fname, 'r') as f:

users_with_geodata = {
    "data": []
}
all_users = []
total_tweets = 0
geo_tweets  = 0
for line in f:
    tweet = json.loads(line)
    if tweet['user']['id']:
        total_tweets += 1 
        user_id = tweet['user']['id']
        if user_id not in all_users:
            all_users.append(user_id)

            #Give users some data to find them by. User_id listed separately 
            # to make iterating this data later easier
            user_data = {
                "user_id" : tweet['user']['id'],
                "features" : {
                    "name" : tweet['user']['name'],
                    "id": tweet['user']['id'],
                    "screen_name": tweet['user']['screen_name'],
                    "tweets" : 1,
                    "location": tweet['user']['location'],
                }
            }
            #Iterate through different types of geodata to get the variable primary_geo
            if tweet['coordinates']:
                user_data["features"]["primary_geo"] = str(tweet['coordinates'][tweet['coordinates'].keys()[1]][1]) + ", " + str(tweet['coordinates'][tweet['coordinates'].keys()[1]][0])
                user_data["features"]["geo_type"] = "Tweet coordinates"
            elif tweet['place']:
                user_data["features"]["primary_geo"] = tweet['place']['full_name'] + ", " + tweet['place']['country']
                user_data["features"]["geo_type"] = "Tweet place"
            else:
                user_data["features"]["primary_geo"] = tweet['user']['location']
                user_data["features"]["geo_type"] = "User location"
            #Add only tweets with some geo data to .json. Comment this if you want to include all tweets.
            if user_data["features"]["primary_geo"]:
                users_with_geodata['data'].append(user_data)
                geo_tweets += 1

        #If user already listed, increase their tweet count
        elif user_id in all_users:
            for user in users_with_geodata["data"]:
                if user_id == user["user_id"]:
                    user["features"]["tweets"] += 1

#Count the total amount of tweets for those users that had geodata            
for user in users_with_geodata["data"]:
    geo_tweets = geo_tweets + user["features"]["tweets"]
#Get some aggregated numbers on the data
print ("The file included ") + str(len(all_users)) + (" unique users who tweeted with or without geo data")
print ("The file included ") + str(len(users_with_geodata['data'])) + (" unique users who tweeted with geo data, including 'location'")
print ("The users with geo data tweeted ") + str(geo_tweets) + (" out of the total ") + str(total_tweets) + (" of tweets.")

with open('analisis_geo.json', 'w') as fout:
fout.write(json.dumps(users_with_geodata, indent=4))

当我在 python 3.6.1 中运行时,出现错误消息: .但在 python 2.7.13 中,脚本可以运行良好,如下所示: .有谁知道如何使脚本与 python 3.6.1 兼容?

【问题讨论】:

    标签: python python-2.7 python-3.x twitter


    【解决方案1】:

    Python 3 dict.keys() 返回不同类型的对象。为了通过索引访问键,您需要将其转换为list。所以

    keys = list(my_dict.keys())[0]

    您也可以像在 for 循环中那样遍历键,但这在这里并不能真正帮助您。

    for key in my_dict.keys():
        # do things
    

    【讨论】:

    • 你能告诉我脚本的哪一部分需要编辑吗?不好意思,因为我不懂Python,所以脚本是从网上找的。​​span>
    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2019-11-12
    相关资源
    最近更新 更多