python - 应用 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,
})
解决方案
getattr
它的default
参数是你所追求的:
author = getattr(tweet, "author", None)
contributors = getattr(tweet, "contributors", None)
coordinates = getattr(tweet, "coordinates", None)
如果第二个参数描述的属性不存在,则返回第三个参数。
推荐阅读
- python - 具有多进程和 joblib 的 Python
- css - React-Table 组件的样式
- android - Android Studio 中的配置 - 无法找到或加载主类
- node.js - 在 NPM 6.14.4 上从终端创建新的 React 应用程序时出错
- r - R:SpatialPointsDataFrame 代码不再工作。!res[[1]] 中的错误:无效的参数类型
- vuetify.js - 在默认插槽中动态更改 v-text-field 中的类
- python - Plotly Dash:dcc.RadioItems 垂直对齐
- javascript - 在 Vue JS 中获取组件之间的数据
- python - 基于scrapy的爬虫不提取内容
标签
- influxdb - 如何调试 Telegraf?