0

我正在尝试使用 python 创建一个小型查找程序,该程序将显示理论投资组合的所有当前价格,然后提供基本刷新您的投资组合的选项,或查找您选择的新报价。

我可以让程序中的一切正常工作,我遇到的问题是定义的函数。

如果您查看 run_price1(),您会注意到它与 run_price() 相同;但是 run_price() 位于更新函数中。

如果我将其从更新功能中取出,更新功能将不起作用。如果我没有在更新功能之外的某个地方也列出它,那么以后的用户输入将不起作用。

问题:我正在寻找一种方法来调用在另一个函数中定义的函数,或者一种在辅助函数中使用先前定义的函数的方法。

我的代码:

import mechanize

from bs4 import BeautifulSoup


def run_price1():

    myBrowser = mechanize.Browser()
    htmlPage=myBrowser.open(web_address)
    htmlText=htmlPage.get_data()
    mySoup = BeautifulSoup(htmlText)

    myTags = mySoup.find_all("span", id=tag_id)

    myPrice = myTags[0].string

    print"The current price of, {} is: {}".format(ticker.upper(), myPrice)



def update():

    my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]

    counter = 0

    while counter < len(my_stocks):

        web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
        ticker = my_stocks[counter]
        #'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
        tag_id = "yfs_l84_{}".format(ticker.lower())
        def run_price():

            myBrowser = mechanize.Browser()
            htmlPage=myBrowser.open(web_address)
            htmlText=htmlPage.get_data()
            mySoup = BeautifulSoup(htmlText)

            myTags = mySoup.find_all("span", id=tag_id)
            myPrice = myTags[0].string
            print"The current price of, {} is: {}".format(ticker.upper(), myPrice)

        run_price()

        counter=counter+1

update()        

ticker = ""

while ticker != "end":

    ticker = raw_input("Type 'update', to rerun portfolio, 'end' to stop program, or a lowercase ticker to see price: ")
    web_address = "http://finance.yahoo.com/q?s={}".format(ticker.lower())
    tag_id = "yfs_l84_{}".format(ticker.lower())

    if ticker == "end":
        print"Good Bye"

    elif ticker == "update":
        update()

    else:
        run_price1()
4

1 回答 1

0

您可以简单地run_price1()update()函数调用,现在调用run_price.

在模块顶部定义的函数在模块中是全局的,因此其他函数可以简单地通过名称引用并调用它们。

您的函数需要的任何值需要作为参数传入:

def run_price1(web_address, tag_id):
    # ...

def update():
    my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]

    counter = 0

    while counter < len(my_stocks):

        web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
        ticker = my_stocks[counter]
        #'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
        tag_id = "yfs_l84_{}".format(ticker.lower())

        run_price1(web_address, tag_id)

        counter=counter+1
于 2013-04-01T15:30:56.180 回答