首页 > 解决方案 > 应用 try 除了多个属性

问题描述

我有 tweepy 对象(包含 twitter 数据),其中并非对象中的所有内容都具有每个属性。每当没有属性时,我都想附加一个None值。我想出了以下代码,但它太长了,因为有很多属性,我正在为每个属性应用一个 try-except 块。我刚刚展示了前 3 个属性,因为它们有很多。只是好奇是否有更好的方法来做到这一点?

注意:必须添加带有属性错误的异常,因为并非所有内容都具有所有属性,因此每当迭代没有该属性的内容时都会引发错误。例如,在第一次迭代期间tweet.author,tweet.contributors,tweet.coordinates可能存在。但是在第二次迭代中tweet.contributors,tweet.coordinates可能只存在,并且当 python 抛出一个AttributeError

 from tweepy_streamer import GetTweets
 inst = GetTweets()
 # tweepy API object containing twitter data such as tweet, user etc
 twObj = inst.stream_30day_tweets(keyword = 'volcanic disaster', search_from = '202009010000', search_to = '202009210000')

 tweet_list = []

for tweet in twObj:
    try:
        author = tweet.author
    except AttributeError:
        author = None
    try:
        contributors = tweet.contributors
    except AttributeError:
        contributors =None 
    try:
        coordinates = tweet.coordinates
    except AttributeError:
        coordinates = None
 
    # Append to a list of dictionaries in order to construct a dataframe
    tweet_list.append({
        'author' : author,
        'contributors' : contributors,
        'coordinates' : coordinates,
        })

标签: pythonoop

解决方案


getattr它的default参数是你所追求的:

author = getattr(tweet, "author", None)
contributors = getattr(tweet, "contributors", None)
coordinates = getattr(tweet, "coordinates", None)

如果第二个参数描述的属性不存在,则返回第三个参数。


推荐阅读