Python学习之 PrettyTable 用例



from prettytable import PrettyTable
pt = PrettyTable()

pt.field_names=[i for i in range(1,10)]

mulp=[["{b}x{a}={c}".format(a=a,b=b,c=a*b) if a>=b else "" for b in range(1,10)] for a in range(1,10)]
map(pt.add_row,mulp)

print(pt)

作者:陈二白
链接:https://www.zhihu.com/question/50034227/answer/119749934
来源:知乎
著作权归作者所有,转载请联系作者获得授权。



之前weather 天气爬虫 用prettytable优化后

#coding=utf-8
import requests
import re
import argparse
from bs4 import BeautifulSoup
from prettytable import PrettyTable

parser = argparse.ArgumentParser()
parser.add_argument('-c','--city',default='hangzhou')
args = parser.parse_args()
city = args.city

url = 'http://weather.sina.com.cn/'+city
response = requests.get(url)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text,'html.parser')

city = soup.find(class_='slider_ct_name').string.encode('utf-8')
date = []
weather = []
temperature = []

pt = PrettyTable(['date','daytime','night','tempeature'])
pt.align['日期']='1'
#get date
for item in soup('p',class_='wt_fc_c0_i_date'):
	date.append(unicode(item.string).encode('utf-8'))
#get weather
for item in soup("img", {"class": 'icons0_wt'}):
	weather.append(item['alt'].encode('utf-8'))
#get temperature
for item in soup('p',class_='wt_fc_c0_i_temp'):
	temperature.append(item.string.encode('utf-8'))

# txt = ''
# txt += city + '10日天气:\n'
# for counter in range(9):
# 	txt += date[counter] +'\t' +'day:' + weather[2*counter] +'\t\t\t'+'nignt:'+weather[2*counter+1]+'\t\t'
# 	txt += temperature[counter]
# 	txt +='\n'
# print txt

#make table
for counter in range(9):
	currow =[]
	currow.append(date[counter])
	currow.append(weather[2*counter])
	currow.append(weather[2*counter+1])
	currow.append(temperature[counter])
	pt.add_row(currow)

filename = city + '10日天气'+'.txt'
with open(filename,'w') as fp:
	fp.write('\t\t\t'+city+'10日天气\n')
	fp.write(str(pt))

虽然中文仍然出现了无法对齐的问题(由于utf-8占用2个字节)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值