溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

發(fā)布時(shí)間:2022-06-20 09:14:26 來(lái)源:億速云 閱讀:172 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格”,在日常操作中,相信很多人在python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

前言:

大多數(shù)時(shí)候,需要輸出的信息能夠比較整齊的輸出來(lái),在使用mysql的時(shí)候,我們使用命令符之后,會(huì)輸出特別好看的表格,python的prettytable庫(kù)就是這么一個(gè)工具,可以幫助我們打印出好看的表格,并且對(duì)中文支持特別友好

安裝

prettytable是pyhton內(nèi)置庫(kù),通過(guò)命令直接可以安裝

pip install prettytable

案例

from prettytable import PrettyTable

table = PrettyTable(['姓名', 'ID', 'Salary'])
table.add_row(['Phil', '0001', '10000'])
table.add_row(['Joge', '0002', '30000'])
print(table)

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

按行添加數(shù)據(jù)table.add_row()
還可以實(shí)現(xiàn)按列添加數(shù)據(jù)table.add_column()

這里會(huì)有一些不一樣的地方:

先使用**PrettyTable()**創(chuàng)建好表格,add_column(x,[]),x為列名,[]后面的列表為每列的值

import sys
from prettytable import PrettyTable

table = PrettyTable()
table.add_column('姓名', ['Phil', 'Joge'])
table.add_column('ID',['0002', '0001'])
print(table)

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

從csv文件添加數(shù)據(jù),并打印出表格

目前prettytable支持csv,不支持xlsx

from prettytable import PrettyTable
from prettytable import from_csv

table = PrettyTable()
file = open('test.csv','r')
table = from_csv(file)
print(table)
file.close()

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

從HTML導(dǎo)入數(shù)據(jù)

from prettytable import PrettyTable
from prettytable import from_html

html = '''
<table>
<str>
<tr>
<th>姓名</th>
<th>ID</th>
</tr>
<tr>
<td>Vergil</td>
<td>001</td>
</tr>
<tr>
<td>Dante</td>
<td>002</td>
</tr>
</table>'''
table = from_html(html)
print(table)

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

還有支持sql輸入,這里就不演示了
prettytable還支持自定義表格的樣式、表格切片、輸出指定的行等功能

這里演示下自定義表格:

from prettytable import PrettyTable
from prettytable import from_csv

table = PrettyTable()
file = open('test.csv','r')
table = from_csv(file)

table.border = True
table.junction_char = '%'
table.horizontal_char = '+'
table.vertical_char = '^'
print(table)
file.close()

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格

到此,關(guān)于“python怎么使用prettytable內(nèi)置庫(kù)美化輸出表格”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI