Python 除多个属性外应用try
我有一个tweepy对象(包含twitter数据),对象中的所有内容并非都具有所有属性。只要没有属性,我就想附加一个Python 除多个属性外应用try,python,oop,Python,Oop,我有一个tweepy对象(包含twitter数据),对象中的所有内容并非都具有所有属性。只要没有属性,我就想附加一个None值。我已经提出了以下代码,但它太长了,因为有很多属性,我正在为每个属性应用一个try-except块。我刚刚展示了前3个属性,因为有很多em。只是好奇是否有更好的方法来实现这一点 注意:必须添加带有属性错误的异常,因为并非所有内容都具有所有属性,因此每当迭代不具有该属性的内容时,都会抛出错误。 例如,在第一次迭代期间,可能存在tweet.author、tweet.contr
None
值。我已经提出了以下代码,但它太长了,因为有很多属性,我正在为每个属性应用一个try-except块。我刚刚展示了前3个属性,因为有很多em。只是好奇是否有更好的方法来实现这一点
注意:必须添加带有属性错误的异常,因为并非所有内容都具有所有属性,因此每当迭代不具有该属性的内容时,都会抛出错误。
例如,在第一次迭代期间,可能存在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,
})
它的默认值
参数就是您想要的:
author = getattr(tweet, "author", None)
contributors = getattr(tweet, "contributors", None)
coordinates = getattr(tweet, "coordinates", None)
如果第二个参数所描述的属性不存在,它将返回第三个参数。及其默认值
参数是您所追求的:
author = getattr(tweet, "author", None)
contributors = getattr(tweet, "contributors", None)
coordinates = getattr(tweet, "coordinates", None)
properties = ('author', 'contributors', 'coordinates')
for tweet in twObj:
tweet_list.append({key:getattr(tweet, key, None) for key in properties})
如果第二个参数描述的属性不存在,它将返回第三个参数
properties = ('author', 'contributors', 'coordinates')
for tweet in twObj:
tweet_list.append({key:getattr(tweet, key, None) for key in properties})