Formato de texto en una tabla en Python
Tengo problemas para crear una tabla que sea dinámica para ajustarse a varios resultados.
He escrito un raspador de pantalla para extraer las acciones dehttp://finance.yahoo.com e imprima el nombre de la empresa, su símbolo y el precio actual de sus acciones.
Sin embargo, la salida se ve así:
Microsoft Corporation MSFT 29.76
Apple Inc. AAPL 396.77
SPDR S&P 500 SPY 155.25
Google Inc. GOOG 787.76
Quiero que se vea como
Microsoft Corporation MSFT 29.76
Apple Inc. AAPL 396.77
SPDR S&P 500 SPY 155.25
Google Inc. GOOG 787.76
Acabo de empezar a trabajar con Python ayer y estoy usando 3.3.1
Mi código actual es el siguiente:
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()
Intenté imprimir ({0}, {1}, {2} .format (namesList, capital, price [i])), varios tipos de {: <16} variaciones, etc. Parece que solo afecta una línea y yo Estoy tratando de hacer que piense en términos de columnas, o una tabla, o tal vez una cierta cantidad de espacio que el texto y el espacio en blanco deben llenar. No estoy seguro de cuál es exactamente la solución, así que les pregunto a todos :)
Como puede ver en mi código, soy bastante nuevo en la programación, así que si hay una mejor manera de hacer algo en este código, me encantaría escuchar correcciones, consejos y sugerencias.