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

查看:28
本文介绍了在 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天全站免登陆