#匿名函数
#结构
lambao x1,x2.... xn: 表达式
sum_num=lambda x1,x2: x1+x2
print(sum_num(2,3))
#参数可以是无限多个,但是列表只有一个
# name_info_list=[
# ('张三', 4500),
# ('李四', 6500),
# ('王五', 7500),
# ('赵六', 2500),
# ]
# name_info_list.sort(key=lambda x:x[1],reverse=True)
# print(name_info_list)
# stu_info = [
# {"name":'zhangsan', "age":18},
# {"name":'lisi', "age":30},
# {"name":'wangwu', "age":99},
# {"name":'tiaqi', "age":3},
# ]
# stu_info.sort(key=lambda i:i['age'])
列表推导式,列表解析个字典解析
之前我们使用普通for 创建列表
# li=[]
# for i in range(10):
# li.append()
# print(i)
#
# #使用列表推导式
# #{表达式 for 临时变量 in可迭代对象 可以追加条件}
# print([i for i in range(10)])
列表解析
筛选出列表中的偶数
# li=[]
# for i in range(10):
# if i%2==0:
# li.append(i)
# print(i)
#
# print({i for i in range(10) if i%2==0})
筛选出列表中大于0的数
from random import randint
num_list=[randint(-10,10) for _ in range(10)]
print(num_list)
print([i for i in num_list if i>0])
字典解析
生成100个学生的成绩
stu_grades={'student{}'.format(i):randint(50,100) for i in range(1,101)}
print(stu_grades)
#筛选大于60分的所有学生
print(({k:v for k,v in stu_grades.items() if v>60}))
正、余弦曲线图
x=np.linspace(0,2*np.pi,num=100)
print(x)
y=np.sin(x)
cosy=np.cos(x)
plt.plot(x,y,color='g',linestyle='--')
plt.plot(x,cosy,color='r')
plt.xlabel('时间(s)')
plt.ylabel('电压(v)')
plt.title('欢迎来到Python')
plt.legend()
plt.show()
图像显示
导入
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
...
柱状图
# import string
# from random import randint
# #字母大写
# print(string.ascii_uppercase[0:6])
# #{'A','B','C' ...}
# x=['口红{}'.format(x) for x in string.ascii_uppercase[0:5]]
# y=[randint(200,500) for _ in range(5)]
# print(x)
# print(y)
# plt.xlabel('口红品牌')
# plt.ylabel('价格(元)')
# plt.bar(x,y)
# plt.show()
饼图
# from random import randint
# import string
# counts=[randint(3500,9000) for _ in range(6)]
# labels=['员工{}'.format(x)for x in string.ascii_lowercase[:6]]
# #距离圆心点的距离
# explode=[0.1,0,0,0,0,0]
# colors=['red','purple','blue','yellow','gray','green']
# plt.pie(counts,explode=explode,shadow=True, labels=labels,autopct = '%1.1f%%',colors=colors)
# plt.legend(loc=2)
# plt.axis('equal')
# plt.show()
散点图
#均值为0,标准差为1的正态分布数据
x=np.random.normal(0,1,10000)
y=np.random.normal(0,1,10000)
plt.scatter(x,y,alpha=0.1)
plt.show()
三国人物分析
import jieba
from wordcloud import WordCloud
1.读取小说内容
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
words=f.read()
count={} #{'曹操':234,'zhouyu':56}
excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
"如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
"东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知"}
2.分词
words_list=jieba.lcut(words)
#print(words_list)
for word in words_list:
if len(word) <= 1:
continue
else:
...
# 更新字典中的值
#counts[word]=取出字典中原来键对应的值+1
#count[word]=count[word]+1
#字典中,get(k) 如果字典中没有这个键,返回NONE
count[word]=count.get(word,0)+1
print(count)
for word in excludes:
del count[word]
3.词语过滤,删除无关词,重复词
count['孔明']=count['孔明']+count['孔明曰']
count['玄德']=count['玄德']+count['玄德曰']+count['刘备']
count['关公']=count['关公']+count['云长']
4.排序
items=list(count.items())
print(items)
def sort_by_count(x):
return x[1]
items.sort(key=sort_by_count,reverse=True)
#items.sort(key=lambda )
li=[] #{'kkkk'}
for i in range(10):
#序列解包
role,count=items[i]
print(role,count)
#_是告诉看代码的人,循环里面不需要使用临时变量
for _ in range(count):
li.append(role)
5.得出结论
text =' '.join(li)
WordCloud(
font_path='msyh.ttc',
background_color='white',
width=800,
height=600,
collocations=False
).generate(text).to_file('TOP10.png')