Python 100天-從新手到大師學習筆記番外篇:好玩的Python
3 min readJun 20, 2019
iPython
因为下面的代码都非常简单,简单到直接使用Python的交互式环境就能完成。当然,官方Python自带的交互式环境比较难用,推荐大家使用ipython,可以使用下面的命令来安装ipython,安装成功后键入ipython命令就能进入交互式环境。
pip install ipython
或
pip3 install ipython
ipython最直观的优点:
- 可以用?或者??来获取帮助。
- 可以用!调用系统命令。
- 可以使用Tab键自动补全。
- 可以使用魔法指令,如:%timeit。
Pillow
pip install pillow
或
pip3 install pillow
加载图片。
from PIL import Image
chiling = Image.open(‘chiling.jpg’) chiling.show()
使用滤镜。
from PIL import ImageFilter
chiling.filter(ImageFilter.EMBOSS).show()
chiling.filter(ImageFilter.CONTOUR).show()
图像剪裁和粘贴。
rect = 220, 690, 265, 740
watch = chiling.crop(rect)
watch.show()
blured_watch = watch.filter(ImageFilter.GaussianBlur(4))
chiling.paste(blured_watch, (220, 690))
chiling.show()
生成镜像。
chiling2 = chiling.transpose(Image.FLIP_LEFT_RIGHT)
chiling2.show()
生成缩略图。
width, height = chiling.size
width, height = int(width * 0.4), int(height * 0.4)
chiling.thumbnail((width, height))
合成图片。
frame = Image.open('frame.jpg')
frame.show()
frame.paste(chiling, (210, 150))
frame.paste(chiling2, (522, 150))
frame.show()
Requests模組
pip install requests
或
pip3 install requests
爬取新闻数据或者通过API接口获取新闻数据。
import requestsresp = requests.get('http://api.tianapi.com/allnews/?key=请使用自己申请的Key&col=7&num=50')
使用反序列化将JSON字符串解析为字典并获取新闻列表。
import json
newslist = json.loads(resp.text)['newslist']
对新闻列表进行循环遍历,找到感兴趣的新闻,例如:华为。
for news in newslist:
title = news['title']
url = news['url']
if '华为' in title:
print(title)
print(url)