我在创建动态表以适应各种结果时遇到问题。
我写了一个屏幕刮板来从http://finance.yahoo.com提取股票并打印公司名称、符号和当前股价。
但是输出看起来像这样:
Microsoft Corporation MSFT 29.76
Apple Inc. AAPL 396.77
SPDR S&P 500 SPY 155.25
Google Inc. GOOG 787.76
我希望它看起来像
Microsoft Corporation MSFT 29.76
Apple Inc. AAPL 396.77
SPDR S&P 500 SPY 155.25
Google Inc. GOOG 787.76
我昨天刚开始使用 Python 并且正在使用 3.3.1
我目前的代码如下:
import re
import urllib.request
import cgi
from bs4 import BeautifulSoup
price = [0,0,0,0]
namesList = ["string1", "string2", "string3", "string4"]
stocksList = ["msft","aapl","spy","goog"]
def HTML():
i = 0
while i < len(stocksList):
htmlPull = urllib.request.urlopen("http://finance.yahoo.com/q?s="+stocksList[i]+"&ql=1")
htmlPull = htmlPull.read().decode('utf-8')
regex = '<span id="yfs_l84_'+stocksList[i]+'">(.+?)</span>'
pattern = re.compile(regex)
price[i] = re.findall(pattern,htmlPull)
htmlParse = BeautifulSoup(htmlPull)
title = htmlParse.title.contents
namesList[i] = title
i+=1
formatPrice(price)
formatStock(namesList)
formatOutput(namesList, stocksList, price)
def formatPrice(price):
k=0
while k < len(price):
cleaner = str(price[k])
cleaner = cleaner.replace("[","")
cleaner = cleaner.replace("]","")
cleaner = cleaner.replace("'","")
price[k] = float(cleaner)
k+=1
def formatStock(namesList):
k = 0
while k <len(namesList):
capital = stocksList[k]
capital = capital.upper()
cleaner = str(namesList[k])
cleaner = cleaner.replace("Summary for ", "")
cleaner = cleaner.replace(":"," ")
cleaner = cleaner.replace("- Yahoo! Finance'","")
cleaner = cleaner.replace("['","")
cleaner = cleaner.replace("]","")
cleaner = cleaner.replace(";","")
cleaner = cleaner.replace(capital, "")
namesList[k] = cleaner;
k+=1
def formatOutput(namesList, stocksList, price):
i = 0
while i < len(price):
capital = stocksList[i]
capital = capital.upper()
print(namesList[i],capital, price[i])
print("")
i+=1
HTML()
尝试过 print ({0},{1},{2}.format (namesList, capital, price[i])),各种类型的 {:<16} 变体等。它似乎只影响一行,我'试图让它根据列、表格或文本和空白应该填充的一定空间来思考。我不确定这里的解决方案到底是什么,所以我问大家:)
从我的代码可以看出,我对编程很陌生,所以如果在这段代码中有更好的方法来做任何事情,我很乐意听取更正、建议和建议。