【问题标题】:Run function multiple times without updating over previous result python多次运行函数而不更新以前的结果python
【发布时间】:2021-11-16 11:15:24
【问题描述】:

我正在使用 twitter API 并编写了以下函数:

import tweepy
import pandas as pd
import traceback
import datetime

def tweets(username, count):
    
    df = pd.DataFrame()
    data = {}

    try:
        for tweet in tweepy.Cursor(api.user_timeline,id=username).items(count):
            
            timesince = datetime.datetime.utcnow() - tweet.created_at #calculate the time since tweet was posted
            ipm = (tweet.favorite_count + tweet.retweet_count) / (abs(int(timesince.total_seconds() / 60))) #interactions per minute

            data['retweets'] = tweet.retweet_count
            data['favorites'] = tweet.favorite_count
            data['total_interactions'] = tweet.favorite_count + tweet.retweet_count
            data['ipm'] = ipm #interactions per minute
            
            df = df.append(data, ignore_index=True)
            
        return df
    except tweepy.RateLimitError:
        print("Rate limit exceeded")
    except tweepy.TweepError as err:
        print("Error: %s" % err.reason)
    except Exception:
        traceback.print_exc()

这个想法是多次运行这个函数并为每分钟的交互创建一个日志。此函数的当前输出是一个数据框,其中包含函数中定义的 4 列。但是,我希望每分钟的交互次数列在每次运行函数时添加新的 IPM 值(例如每次运行函数时为每条推文创建 IPM 列表),而不是仅仅更新旧值。我尝试创建一个全局变量并将其附加到该变量,因此每次运行该函数时,数据都不会丢失,但这不起作用,因为它被视为不同的推文,而不是已收集的推文的更新。苏有什么想法吗?任何帮助表示赞赏!我认为这更像是一个 python 问题,而不是 twitter API 问题

【问题讨论】:

    标签: python pandas twitter tweepy


    【解决方案1】:

    您可以使用data.clear() 显示或保存数据后,使用函数.clear() 清空列表以获取新数据以覆盖它。

    谢谢!

    【讨论】:

    • 抱歉,如果我误解了,但我想补充从上次运行该函数收集的数据。例如,我为一条推文运行一次,IPM 列中的值为 5。当我第二次运行它时,我希望输出为 [5, x] - 其中 x 是 IPM 的更新值。因此,我不想将 x 替换为 5,而是将其添加到 5 旁边
    • 数据是放在data还是df中?
    • 这是一个更大的函数的一部分,最后,数据将被放置在dfdata
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2022-12-12
    • 1970-01-01
    • 2012-02-11
    相关资源
    最近更新 更多