在Python中格式化表格中的文本 [英] Formatting Text in a Table in Python

查看:81
本文介绍了在Python中格式化表格中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建动态调整表格以适应各种结果时遇到问题.

I'm having issues creating a table that is dynamic to adjust to various results.

我编写了一个屏幕抓取工具,以从 http://finance.yahoo.com 和打印公司名称,符号和当前股价.

I've written a screen scraper to pull stocks from http://finance.yahoo.com and print the company name, it's symbol, and it's current stock price.

但是输出看起来像这样:

However the output looks like this:

 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

I just started wokring with Python yesterday and am using 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()

尝试打印({0},{1},{2} .format(namesList,capital,price [i])),各种类型的{:< 16}变体等,它似乎只会影响一行,我试图让它根据列,表或可能需要填充文本和空白的一定数量的空间来思考.我不确定解决方案到底是什么,所以我问大家:)

Have tried print ({0},{1},{2}.format (namesList, capital, price[i])), various types of {:<16} variations, etc. It seems to only affect one line and I'm trying to get it to think in terms of columns, or a table, or maybe a certain amount of space that the text and whitespace should fill. I'm not sure what exactly the solution is here, so I'm asking you all :)

您可以从我的代码中看出,我是编程的新手,因此,如果有更好的方法可以在此代码中执行任何操作,我将很乐意听取纠正,建议和建议.

As you can tell by my code, I'm pretty new to programming, so if there is a better way to do anything in this code, I'd be happy to listen to correction, advice, and suggestions.

推荐答案

您要基于列中最长的项设置宽度.

You want to set the width based on the longest item in the column.

在Python中,您使用max查找某些事物中最大的事物.因此,在循环之外,您可以执行以下操作:

In Python, you use max to find the largest of some group of things. So, outside the loop, you can do:

names_width = max(len(name) for name in namesList)
stock_width = max(len(stock) for stock in stockList)

然后,按照您说过的方式格式化每一行:

Then, format each line like you said you tried:

print({0:{3}}  {1:{4}}  {2}.format(namesList[i],
                                   capital,
                                   price[i],
                                   names_width,
                                   stock_width))

这篇关于在Python中格式化表格中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆