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个字节)