列表推导式
格式 [表达式 for 临时变量 in 可迭代对象 [条件语句]]
用途:快速生成一个列表
- 使用普通for循环创建列表
li = []
for 临时变量 in 可迭代对象
# 循环体
for i in range(10):
# 向列表中添加元素
li.append(i)
print(li)
# 以上我们使用4行代码显示一个0~9的列表
li2 = [i for i in range (10)]
print(li2)
print([i for i in range (10)])
- 生成随机数
from random import randint
print(randint(60,100))
- 生成一个列表 ['序号:998','序号:998','序号:998']共10个元素
#普通for循环
# from random import randint
# li = []
# for _ in range(10): #下划线是给读代码人看的 ,表示下面将不使用—_
# li.append("序号{}".format(randint(100, 999)))
# print(li)
- 使用列表推导式生成一个含有20个元素的随机数列表[]
删选出 所有奇数
from random import randint
li = [randint(30, 100) for _ in range(20)]
print(li)
print([x for x in li if x%2 ==1 ])
1234
三目运算符
格式:
返回值 if 满足条件的表达式 else 不满足时要执行的事情
#如何使用一行的 if else?
li = ['dada']
# if len(li)==0:
# li = 'aa'
# else:
# li = li[0]
# print(li)
s = 'aa' if len(li) == 0 else li[0]
print(s)
123456789
爬取豆瓣即将上映电影信息功能加强版
- 加强功能:增加了图片爬取功能
import requests
from lxml import html
import pandas as pd
from xpinyin import Pinyin
from matplotlib import pyplot as plt
# 设置支持中文字体
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def spider(city):
city_pinyin = Pinyin().get_pinyin(city, splitter='')
url = 'https://movie.douban.com/cinema/later/{}'.format(city_pinyin)
print(url)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"}
html_data = requests.get(url, headers=headers).text
selector = html.fromstring(html_data)
div_list = selector.xpath('//div[@id = "showing-soon"]/div')
print('共有{}部即将上映的电影'.format(len(div_list)))
movie_info_list = []
for div in div_list:
# 电影名字
movie_name = div.xpath('div/h3/a/text()')[0]
if len(movie_name)==0:
movie_name = '没有查询到数据'
else:
movie_name = movie_name
# 上映时间
date = div.xpath('div/ul/li[1]/text()')[0]
if len(date)==0:
date = '没有查询到数据'
else:
date = date
# 电影类型
type = div.xpath('div/ul/li[2]/text()')[0]
if len(type)==0:
type = '没有查询到数据'
else:
type = type
# 电影国家
countries = div.xpath('div/ul/li[3]/text()')[0]
if len(countries)==0:
countries = countries
# 电影想看人数
num = div.xpath('div/ul/li[4]/span/text()')[0]
num = num.replace('人想看', '')
if len(num)==0:
num = '没有查询到数据'
else:
num = num
# 图片链接
img_link = div.xpath('a/img/@src')[0]
movie_info_list.append({
"movie_name" : movie_name,
"date" : date,
"type" : type,
"countries" : countries,
"num" : num,
"img_link":img_link
})
movie_info_list.sort(key=lambda x: int(x['num']), reverse=True)
for movie in movie_info_list:
print(movie)
# 图片爬取
with open('./douban_img/{}.jpg'.format(movie['movie_name']), 'wb') as f:
f.write(requests.get(movie['img_link']).content)
for movie in movie_info_list:
print(movie)
df = pd.DataFrame(movie_info_list)
df.to_csv('豆瓣即将上映电影信息.csv')
city = input('请输入城市:')
spider(city)
绘制线型图
- 绘制 正弦曲线
- 选取100个等间距的点(x,y)然后进行绘制曲线
- 生成[0,2π]区间100哥等间距的点
x = np.linspace(0,2*np.pi,num=100)
print(x)
y = np.sin(x)
cosy = np.cos(x)
# 绘制
plt.plot(x,y,
color = 'b',# 线的颜色
linestyle=':',#线的风格 -代表实线 --虚线 :点画线
marker='o',#标记点的样式 o 实心圆 * +
markerfacecolor='r',#标记点的颜色
alpha=0.8,#设置透明度
label = 'sin(x)'
)
plt.plot(x,cosy,
color = 'r',
linestyle = '--',
marker = '*',
markerfacecolor = 'r',
alpha = 1,
label = 'cos(x)'
)
plt.xlabel('time(s)')
plt.ylabel('电压')
plt.title('点压随时间变化曲线')
plt.legend()#设置图例
plt.show()
绘制条形图
from random import randint
x = ['口红{}'.format(i) for i in range(1,7)]
print(x)
y = [randint(200,1000)for _ in range(6)]
print(y)
plt.bar(x,y)
plt.grid()
plt.xlabel('口红品牌')
plt.ylabel('口红价格(元)')
plt.show()