我只是学习python而无法想出一种更有效的方法来编写一组代码。代码查看API调用的结果,并将特定文本提取到单元格中(最终进入Excel)。当它找不到特定文本时,它会返回该特定单元格的“NA”。我目前编写的方式是:
try:
company = 'company name in API output' #path to the value of the key that matches company name
except:
company:'NA' #Sometimes, the company name isn't in the API output and this results in an IndexError, so it should return 'NA' in the specific cell
try:
location = 'location of company in API output' #path to the value of the key that matches location
except:
location = 'NA'
# etc... This data eventually gets appended to a table row by row and then exported to pandas if that is helpful to know.
代码运行正常,所以我不需要那方面的帮助。我想要输入的是是否有更好的方法来编写代码,可能使用函数或其他python代码,这样我就不必对每个变量进行try / excepts,而是以某种方式编写,以便均匀如果一个变量导致错误,并非所有变量都变为“NA”。在此先感谢您的帮助!