我才开始用python编写代码大约一个月。我可以覆盖以前解析的数据吗?问题在正文中继续

2024-06-28 11:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个函数,在从yahoo finance解析特定股票后,它将收集该股票的信息。现在在功能结束时,我会让用户选择搜索其他报价或返回主页。当用户单击此选项时,程序崩溃,表示数组的长度必须相同。我假设,因为从上一个引用中收集的数据已经在函数中注册,并且不允许用户覆盖和解析。我如何解决这个问题?请告知

import random
import requests
import numpy as np
import pandas as pd 

def tickersymbol():
    tickersymbol = input("What company would you like information on?") 
    url = ('https://ca.finance.yahoo.com/quote/'+tickersymbol+'?p='+tickersymbol+'&.tsrc=fin-srch')
    response = requests.get(url) 
    htmltext = response.text

    for indicator in Indicators :

        splitlist = htmltext.split(indicator)
        afterfirstsplit =splitlist[1].split("\">")[2]
        aftersecondsplit = afterfirstsplit.split("</span>")
        datavalue = aftersecondsplit[0]
        Indicators[indicator].append(datavalue)

    for values in Misc:
        splitlist = htmltext.split(values)
        afterfirstsplit =splitlist[1].split("\">")[1]
        aftersecondsplit = afterfirstsplit.split("</td>")
        netset = aftersecondsplit[0]
        Misc[values].append(netset)

    Indicators.update(Misc)
    df = pd.DataFrame(Indicators)
    array = np.transpose(df)
    print(array)

    task = input('''
                 Would you like to continue? 

                 [1] : Yes, Look at another Symbol     ##Here is where the problem starts. 
                 [2] : No, Go back to main 

                   ''')

    if task == "1":
        return tickersymbol()
    elif task == "2":
        return main()
    else:
        print("Try to answer that one again")

指标=

{“前收盘价”:[],“开盘价”:[],“买入价”:[],“卖出价”:[],“成交量”:[],“平均成交量”:[],“市值”:[],“Beta”:[],“市盈率(TTM)”:[],“每股收益(TTM)”:[],“除息日”:[],“1y目标Est:[]]

杂项=

{'52周范围':[],“日范围”:[],'股息和收益':[]


Tags: to函数用户importtaskindicatormiscsplit
1条回答
网友
1楼 · 发布于 2024-06-28 11:37:15

发现的软件问题如下:

tickersymbol = input("What company would you like information on?") 

由于这与函数名相同,因此在再次尝试调用函数时会导致错误,即

return tickersymbol()

补救措施,将行更改为:

tickersymbol_ = input("What company would you like information on?") 
url = ('https://ca.finance.yahoo.com/quote/'+tickersymbol_+'?p='+tickersymbol_+'&.tsrc=fin-srch')

其他修订版

  1. 检查使用try/except块时出错

  2. 控制流使用while循环,而不是函数调用自身

  3. 指示器和杂项内部功能,以便为处理的每个库存重置它们

  4. main调用tickersymbol,完成后返回

修订代码

import random
import requests
import numpy as np
import pandas as pd 

def main():
  tickersymbol()

def tickersymbol():
    while True:
      skip = False

      tickersymbol_ = input("What company would you like information on?") 
      url = ('https://ca.finance.yahoo.com/quote/'+tickersymbol_+'?p='+tickersymbol_+'&.tsrc=fin-srch')
      response = requests.get(url) 
      htmltext = response.text

      # Reset Indicator and Misc
      Indicators = {"Previous Close" : [], "Open" : [], "Bid" : [] , "Ask": [], 'Volume': [], 'Avg. Volume': [], 'Market Cap': [], 'Beta': [], 'PE Ratio (TTM)': [], 'EPS (TTM)': [], 'Earnings Date': [], 'Ex-Dividend Date': [], '1y Target Est' : []} 

      Misc = {'52 Week Range' :[], "Day&#x27;s Range": [], 'Dividend &amp; Yield' : []} 

      for indicator in Indicators :
          try:
            splitlist = htmltext.split(indicator)
            afterfirstsplit =splitlist[1].split("\">")[2]
            aftersecondsplit = afterfirstsplit.split("</span>")
            datavalue = aftersecondsplit[0]
            Indicators[indicator].append(datavalue)
          except:
            print('Error with stock')
            skip = True
            break

      if skip:
        continue     # continues with the outer while loop

      for values in Misc:
          try:
            splitlist = htmltext.split(values)
            afterfirstsplit =splitlist[1].split("\">")[1]
            aftersecondsplit = afterfirstsplit.split("</td>")
            netset = aftersecondsplit[0]
            Misc[values].append(netset)
          except:
            print('Error with stock')
            skip = True
            break

      if skip:
        continue    # continues with outer while loop

      Indicators.update(Misc)
      df = pd.DataFrame(Indicators)
      array = np.transpose(df)
      print(array)

      task = input('''
                  Would you like to continue? 

                  [1] : Yes, Look at another Symbol     ##Here is where the problem starts. 
                  [2] : No, Go back to main 

                    ''')

      if task == "1":
          continue    # continues with outer while loop
      elif task == "2":
          return      # done with tickersymbol function
      else:
          print("Try to answer that one again")

if __name__ == "__main__":
    main()

相关问题 更多 >