【问题标题】:Tweepy Transform list of tweets(json) into a dataframeTweepy 将推文(json)列表转换为数据框
【发布时间】:2018-07-21 21:02:46
【问题描述】:

我正在尝试通过以下推文列表获取数据框。但是,在线解决方案都没有帮助。

  1. 当我尝试将搜索结果保存在 json 文件中时,我得到

    'dict' 对象没有属性'_json

def write_tweets(推文,文件名): ''' 将推文附加到文件的函数。 '''

使用以下代码:

def write_tweets(tweets, filename):
''' Function that appends tweets to a file. '''

with open(filename, 'a') as f:
    for tweet in tweets:
        json.dump(tweet._json, f)
        f.write('\n')                               
write_tweets(searched_tweets,"data.json")
  1. 尝试将我的结果转换为数据框也失败了:

    DataSet['tweetID'] = [tweet.id for tweeted_tweets]

我的完整代码如下,并返回researched_results 这是一个列表。

import tweepy
import pandas as pd
import json

df= pd.read_excel(dataNLP.xlsx")

IDs = df["TweetID"].tolist()

def load_api():
    ''' Function that loads the twitter API after authorizing
        the user. '''
   # ApI Keys
    consumer_key = "--"
    consumer_secret = "--"
    access_token = "-----"
    access_token_secret = "-"
    #Pass our consumer key and consumer secret to Tweepy's user authentication handler
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    #Pass our access token and access secret to Tweepy's user authentication handler
    auth.set_access_token(access_token, access_token_secret)
    # load the twitter API via tweepy
    return tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True,parser=tweepy.parsers.JSONParser())

#Connect
api = load_api()

#Creating a twitter API wrapper using tweepy
i = 0
#jump 188 as per tweeter api
step = 100
searched_tweets=[]
cant_find_tweets_for_those_ids = []
cant_find_tweets_for_those_ids_whole =[]
while i <= len(IDs):
    for each_id in IDs[i:(i+step)]:
        try:
            new_tweets =   api.api.statuses_lookup(IDs[i:(i+step)])
            print( "found", len(new_tweets),"tweets")
            searched_tweets.extend(new_tweets)
            print( "added", len(searched_tweets),"in searched_tweets")
            i= i + step +1
        except Exception as e:
            cant_find_tweets_for_those_ids.append(each_id)
            cant_find_tweets_for_those_ids_whole.extend(cant_find_tweets_for_those_ids)

示例 ID:597576902212063232、565586175864610817。

预期的数据框结果可能包含以下字段: ID、文本、user_location、hastags、关注者数量、朋友数量、重新推文数量。 有人可以解释我做错了什么,或者我如何从 searched_tweets 列表中获取一个可用的 daframe 和 json 对象?

searched_tweets 列表的一个元素:

{'truncated': False, 'in_reply_to_user_id': 297535251, 'place': None, 'retweet_count': 0, 'created_at': 'Mon Feb 23 20:28:36 +0000 2015', 'in_reply_to_screen_name': 'OutworldDOTA2', 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'favorited': False, 'contributors': None, 'is_quote_status': False, 'geo': None, 'id': 569957017655226369, 'in_reply_to_status_id_str': '569956825057120256', 'in_reply_to_status_id': 569956825057120256, 'coordinates': None, 'in_reply_to_user_id_str': '297535251', 'id_str': '569957017655226369', 'lang': 'en', 'user': {'description': 'Founder, Online Abuse Prevention Initiative. v (gaming account: @grandma_kj)', 'default_profile': False, 'profile_sidebar_border_color': '181A1E', 'name': 'needlessly obscenity-laced', 'time_zone': 'Pacific Time (US & Canada)', 'profile_banner_url': 'link', 'screen_name': 'randileeharper', 'favourites_count': 66157, 'translator_type': 'regular', 'contributors_enabled': False, 'created_at': 'Sat Feb 23 07:27:19 +0000 2008', 'protected': False, 'notifications': False, 'profile_background_color': '1A1B1F', 'following': False, 'id_str': '13857342', 'location': 'Portland, OR', 'entities': {'description': {'urls': [{'url': 'link, 'expanded_url': 'link', 'indices': [45, 68], 'display_url': 'patreon.com/freebsdgirl'}]}, 'url': {'urls': [{'url': 'link': 'link', 'indices': [0, 23], 'display_url': 'blog.randi.io'}]}}, 'id': 13857342, 'utc_offset': -28800, 'has_extended_profile': True, 'profile_sidebar_fill_color': '252429', 'profile_image_url': 'link', 'friends_count': 787, 'verified': True, 'link': 'link', 'profile_background_image_url': 'link', 'profile_link_color': '2FC2EF', 'profile_text_color': '666666', 'is_translator': False, 'lang': 'en', 'geo_enabled': True, 'statuses_count': 123525, 'profile_image_url_link', 'default_profile_image': False, 'url': 'link', 'listed_count': 901, 'followers_count': 20638, 'follow_request_sent': False, 'profile_use_background_image': True, 'profile_background_tile': False, 'is_translation_enabled': False}, 'text': '@OutworldDOTA2 i\'m very entertained that all it takes is "155 IQ" for me to know precisely who is being discussed.', 'retweeted': False, 'entities': {'hashtags': [], 'urls': [], 'symbols': [], 'user_mentions': [{'id_str': '297535251', 'screen_name': 'OutworldDOTA2', 'name': 'Follow Your Leader', 'indices': [0, 14], 'id': 297535251}]}, 'favorite_count': 0}

【问题讨论】:

    标签: python json dataframe tweepy


    【解决方案1】:

    您的代码:

    for tweet in tweets:
        json.dump(tweet._json, f)
    

    tweet._json 返回一个字典。因此出现错误消息。就个人而言,这是我更喜欢这样做的方式。

    如果您只想要推文列表,则声明一个列表并将每个推文字典添加到其中。

    tweet_list = []
    for tweet in tweets:
        tweet_list.append(tweet._json)
    

    然后您可以通过列表索引和字典键访问推文属性。

    print(tweet_list[0].get("text"))
    print(tweet_list[0].get("created_at")
    

    如果您想将列表保存到文件中,您可以使用 pickle。

    import pickle
    
    def pickle_data(filename, tweet_list):
        with open(filename, "wb") as handle:
            pickle.dump(tweet_list, handle, protocol=pickle.HIGHEST_PROTOCOL)
    

    当您要加载文件时,可以直接将其加载回字典列表中。

    def unpickle_data(filename):
        with open(filename, "rb") as handle:
            tweet_list = pickle.load(handle)
        return tweet_list
    

    不确定这正是您要寻找的东西,但我希望您可以使用一些东西。

    【讨论】:

    • 嗨,尼尔,感谢您抽出宝贵的时间。两种解决方案都给出相同的错误。 “列表”对象没有属性“_json”。 Searched_tweets 是推文列表。我希望能够将其保存为 json 格式,然后将其转换为数据框。唯一似乎有效的是
    【解决方案2】:

    感谢您抽出宝贵时间。两种解决方案都给出相同的错误。 “列表”对象没有属性“_json”。 Searched_tweets 是推文列表。我希望能够将其保存为 json 格式,然后将其转换为数据框。唯一似乎有效的是 from pandas.io.json import

    json_normalize
    data_nested = json_normalize(searched_tweets)
    data = data_nested[["entities.hashtags","favorite_count","id","id_str","lang","retweet_count","retweeted","text","user.description","user.entities.description.urls","user.favourites_count","user.follow_request_sent","user.followers_count","user.following","user.friends_count","user.geo_enabled","user.has_extended_profile","user.id","user.id_str","user.is_translation_enabled","user.is_translator","user.lang","user.listed_count","user.location","user.name","user.notifications","user.translator_type","user.verified"]].copy()
    

    我不确定如何转换它并将其保存为 json 文件。

    【讨论】:

    • 欢迎来到 StackOverflow。其中只有代码的答案往往会被标记为删除,因为它们是“低质量”的。请阅读有关回答问题的帮助部分,然后考虑在您的回答中添加一些评论。
    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 2019-02-08
    • 2023-02-23
    • 1970-01-01
    • 2020-09-02
    • 2021-02-09
    • 2018-08-25
    • 2021-09-27
    相关资源
    最近更新 更多