【问题标题】:How to ignore "KeyError" in Python如何在 Python 中忽略“KeyError”
【发布时间】:2020-05-23 21:44:26
【问题描述】:

我正在尝试使用 api“yfinance”在 python 中分析股票。我让程序在大多数情况下运行得很好。但是,当它无法“找到”其中一个字段时,它会出现错误(KeyError)。这是我的代码的 sn-p。

import yfinance as yf
stock = yf.Ticker(stock)
pegRatio = stock.info['pegRatio']
print(pegRatio)
if pegRatio > 1:
    print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
    print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
    print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")

这是错误 回溯(最近一次通话最后): 第 29 行,在 行业 = stock.info['行业'] KeyError: '行业'

我的主要问题是如何让代码基本上忽略错误并运行其余代码?

【问题讨论】:

  • 你能发布完整的错误吗?
  • 这就是所谓的“错误处理”,您可以在网上找到大量相关信息。
  • 如果你想在这里发布代码,请在此处执行```所有代码行```

标签: python error-handling keyerror


【解决方案1】:

Python 中的错误处理

就像Nicolas commented 一样,您会在网络上找到许多教程、博客文章和视频。还有一些涵盖“错误处理”的基本 Python 书籍。

Python 中的控制结构至少包含两个关键字tryexcept,通常命名为try-except block。还有2个可选关键字elsefinally

如何包装你的失败陈述

import yfinance as yf

try: # st art watching for errors
  stock = yf.Ticker(stock)  # the API call may also fail, e.g. no connection
  pegRatio = stock.info['pegRatio']  # here your actual exception was thrown
except KeyError:  # catch unspecific or specific errors/exceptions
  # handling this error type begins here: print and return
  print "Error: Could not find PEG Ratio in Yahoo! Finance response!"
  return 

# the happy path continues here: with pegRatio
print(pegRatio)
if pegRatio > 1:
    print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
    print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
    print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 2013-03-17
    • 2019-04-25
    • 2014-11-12
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多