如何使此代码不那么多余

时间:2019-01-03 14:36:16

标签: python-3.x loops exception

许多代码对我来说似乎是多余的,我想知道是否可以简化它。我认为可以简化以下几个关键位置。

1-所有5个循环的错误异常都相同
2-对于最后3个部分,构造线程,启动线程,然后等待它们完成。他们是否有办法使此部分具有动态性,因此这3个部分可以根据多线程循环的数目而增加或减少?

这是代码

def write_prices():
    for i in tqdm_notebook(range(0,len(stock_ticker.Symbol))):
        try:
            ticker_df=pd.DataFrame(get_data(np.array(stock_ticker.Symbol)[i]))
            ticker_df.to_csv("E:\\Stock Database\\Stock Prices\\%s.txt"%np.array(stock_ticker.Symbol)[i])

        except ValueError:
            print (" ValueError :%s" %np.array(stock_ticker.Symbol)[i])
        except FileNotFoundError:
            print (" FileNotFoundError :%s" %np.array(stock_ticker.Symbol)[i])
        except KeyError:
            print (" KeyError :%s" %np.array(stock_ticker.Symbol)[i])
        except IndexError:
            print (" IndexError :%s" %np.array(stock_ticker.Symbol)[i])       
        except NameError:
            print (" NameError :%s" %np.array(stock_ticker.Symbol)[i])
        except HTTPError:
            print (" HTTPError " )



def write_incomes():
    for i in tqdm_notebook(range(0,len(stock_ticker.Symbol))):
        try:
            ticker_df=pd.DataFrame(get_income_statement(np.array(stock_ticker.Symbol)[i]))
            ticker_df.to_csv("E:\\Stock Database\\Income Statement\\%s.txt"%np.array(stock_ticker.Symbol)[i])

        except ValueError:
            print (" ValueError :%s" %np.array(stock_ticker.Symbol)[i])
        except FileNotFoundError:
            print (" FileNotFoundError :%s" %np.array(stock_ticker.Symbol)[i])
        except KeyError:
            print (" KeyError :%s" %np.array(stock_ticker.Symbol)[i])
        except IndexError:
            print (" IndexError :%s" %np.array(stock_ticker.Symbol)[i])       
        except NameError:
            print (" NameError :%s" %np.array(stock_ticker.Symbol)[i])
        except HTTPError:
            print (" HTTPError " )

def write_balance_sheet():
    for i in tqdm_notebook(range(0,len(stock_ticker.Symbol))):
        try:
            ticker_df=pd.DataFrame(get_balance_sheet(np.array(stock_ticker.Symbol)[i]))
            ticker_df.to_csv("E:\\Stock Database\Balance Sheet\\%s.txt"%np.array(stock_ticker.Symbol)[i])

        except ValueError:
            print (" ValueError :%s" %np.array(stock_ticker.Symbol)[i])
        except FileNotFoundError:
            print (" FileNotFoundError :%s" %np.array(stock_ticker.Symbol)[i])
        except KeyError:
            print (" KeyError :%s" %np.array(stock_ticker.Symbol)[i])
        except IndexError:
            print (" IndexError :%s" %np.array(stock_ticker.Symbol)[i])       
        except NameError:
            print (" NameError :%s" %np.array(stock_ticker.Symbol)[i])
        except HTTPError:
            print (" HTTPError " )



def write_cash_flow():
    for i in tqdm_notebook(range(0,len(stock_ticker.Symbol))):
        try:
            ticker_df=pd.DataFrame(get_cash_flow(np.array(stock_ticker.Symbol)[i]))
            ticker_df.to_csv("E:\\Stock Database\Cash Flow\\%s.txt"%np.array(stock_ticker.Symbol)[i])

        except ValueError:
            print (" ValueError :%s" %np.array(stock_ticker.Symbol)[i])
        except FileNotFoundError:
            print (" FileNotFoundError :%s" %np.array(stock_ticker.Symbol)[i])
        except KeyError:
            print (" KeyError :%s" %np.array(stock_ticker.Symbol)[i])
        except IndexError:
            print (" IndexError :%s" %np.array(stock_ticker.Symbol)[i])       
        except NameError:
            print (" NameError :%s" %np.array(stock_ticker.Symbol)[i])
        except HTTPError:
            print (" HTTPError " )

def write_stats():
    for i in tqdm_notebook(range(0,len(stock_ticker.Symbol))):
        try:
            ticker_df=pd.DataFrame(get_stats(np.array(stock_ticker.Symbol)[i]))
            ticker_df.to_csv("E:\\Stock Database\Statistics\\%s.txt"%np.array(stock_ticker.Symbol)[i])

        except ValueError:
            print (" ValueError :%s" %np.array(stock_ticker.Symbol)[i])
        except FileNotFoundError:
            print (" FileNotFoundError :%s" %np.array(stock_ticker.Symbol)[i])
        except KeyError:
            print (" KeyError :%s" %np.array(stock_ticker.Symbol)[i])
        except IndexError:
            print (" IndexError :%s" %np.array(stock_ticker.Symbol)[i])       
        except NameError:
            print (" NameError :%s" %np.array(stock_ticker.Symbol)[i])
        except HTTPError:
            print (" HTTPError " )

# construct the threads
t1 = threading.Thread(target=write_prices)
t2 = threading.Thread(target=write_incomes)
t3 = threading.Thread(target=write_balance_sheet)
t4 = threading.Thread(target=write_cash_flow)
t5 = threading.Thread(target=write_stats)

# start the threads
[t.start() for t in (t1, t2, t3, t4, t5)]

# wait until they finish
[t.join() for t in (t1, t2, t3, t4, t5)]

1 个答案:

答案 0 :(得分:3)

您的第一个函数可以重写为:

def write_prices():
    for i in tqdm_notebook(range(0,len(stock_ticker.Symbol))):
        try:
            ticker_df=pd.DataFrame(get_data(np.array(stock_ticker.Symbol)[i]))
            ticker_df.to_csv("E:\\Stock Database\\Stock Prices\\%s.txt"%np.array(stock_ticker.Symbol)[i])

        except (ValueError, FileNotFoundError, KeyError, IndexError, NameError, HTTPError) as e:
            print (e, np.array(stock_ticker.Symbol)[i])