Python第三天

基础知识


1)lambda x1,x2....xn:表达式

注意:参数可以是无限多个,但是表达式只有一个

2)列表推导式

[表达式 for 临时变量 in 可迭代对象 可以追加条件]

3)在使用matplotlib 是解决中文乱码

plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

4) .linspace 左闭右闭区间的等差数列
5)绘制图形的常见函数

先导入 from matplotlib import pyplot as plt
import numpy as np
→ plt.plot() ----------------绘图
→ plt.show() ----------------显示图出来
→ plt.plot(x,y,color='g',linestyle='--',label='sin(x)') ------正弦函数
→ plt.plot(x,cosy,color='y',label='cos(x)') --------余弦函数
→ plt.xlabel('时间(s)')---------x坐标
→ plt.ylabel('电压(v)')---------y坐标
→ plt.title('欢迎黄美琳')------------大标题
→ plt.legend()------------会显示什么线是什么函数
→ plt.bar(x,y)----------------绘制柱状图
→ plt.pie(counts)-----------------绘制饼图
→ plt.scatter(x,y,alpha = 0.1)------------透明度

Python例子


一、找出三国演义TOP10人物,并用云词展示出来。

◆ 步骤大致如下
① 读取小说内容 (with open()的方法)
② 分词 (jieba,python第二天有具体的操作流程)
③ 词语过滤,删除无关词,重复词
④ 排序[(),()] (根据次数排序)
⑤ 得到结论
◆ 代码如下

import jieba
from wordcloud import WordCloud
import imageio

#1.读取小说内容
with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:
    words = f.read()

#2.分词
counts = {}  #{'曹操':234,'孔明':56}
excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
                "如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
                "东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
            '孔明曰','玄德曰','刘备','云长'}
words_list = jieba.lcut(words)     #精确模式
#print(words_list)
for word in words_list:
    if len(word) <= 1:
        continue
    else:
       #更新字典中的值
       #counts[word] = #取出字典中原来对应的值 + 1
       #counts[word] = counts[word] + 1  #counts[word]如果没有就要报错
       counts[word] = counts.get(word,0) + 1 #字典.get(k)如果字典中没有这个键,返回值是none
print(len(counts))

#3.词语过滤,删除无关词,重复词
counts['孔明'] = counts['孔明'] + counts['孔明曰']
counts['玄德'] = counts['玄德'] + counts['玄德曰'] + counts['刘备']
counts['关公'] = counts['关公'] + counts['云长']
for word in excludes:
    del counts[word]

#4.排序[(),()]
items = list(counts.items())  #字典转换成列表
def sort_by_count(x):
    return x[1]
items.sort(key = sort_by_count,reverse = True)
print(items)

li=[]  #列表  添加 ['孔明','孔明','孔明','孔明'....,'曹操'....]
for i in range(10):
    #序列解包
    role,count = items[i]
    print(role, count)
    for _ in range(count):  #_是告诉看代码的人,循环里面不需要临时变量
        li.append(role)

#5.得出结论
text = " ".join(li)  #列表转换成字符串
print(text)
mask = imageio.imread('./china.jpg')
wc = WordCloud(
        font_path = 'msyh.ttc',
        background_color='white',
        width = 800,
        height = 600,
        mask = mask,
        collocations = False  #相邻两个重复词之间的匹配
    ).generate(text).to_file("./三国演义TOP10.png")

◆ 结果如下


二、用lambda的方式排序

name_info_list = [
    ('黄美琳',56612),
    ('hml',13031),
    ('张三',28496),
    ('十年',54151),
    ('女主持',26162)
]
name_info_list.sort(key = lambda x:x[1],reverse=True)
print(name_info_list)

stu_info=[
    {'name':'黄美琳','age':18},
    {'name':'hml','age':20},
    {'name':'张三','age':22},
    {'name':'十年','age':12},
    {'name':'女主持','age':33}
]
stu_info.sort(key = lambda i:i['age'])
print(stu_info)

三、筛选出列表中所有的偶数

◆ 第一种方式

li = []
for i in range(10):
    if i % 2 == 0:
        li.append(i)
print(li)

◆ 第二种方式

print([i for i in range(10) if i % 2 ==0]) 

四、随机产生10个数,筛选出列表中大于 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个学生的成绩,筛选大于60分的所有学生

stu_grades = {'student{}'.format(i):randint(50,100) for i in range(1,101)}
print(stu_grades)
#{k:v for k,v in stu_grades.items()} #遍历 还没有筛选
{k:v for k,v in stu_grades.items() if v > 60}

六、使用100个点 绘制[0,2Π]正弦曲线图

x = np.linspace(0,2*np.pi,num=100)  #范围是[0,2Π] 画100个点
y = np.sin(x)
#plt.plot(x,y,color = 'g')
#plt.show()

#正弦和余弦在同一坐标系下
cosy = np.cos(x)
plt.plot(x,y,color='g',linestyle='--',label='sin(x)')
plt.plot(x,cosy,color='y',label='cos(x)')
plt.xlabel('时间(s)')
plt.ylabel('电压(v)')
plt.title('欢迎黄美琳')
#图例
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])
x = ['口红{}'.format(x) for x in string.ascii_uppercase[:5]]
y = [randint(200,500) for _ in range(5)]
print(x)
print(y)
plt.xlabel('口红品牌')
plt.ylabel('价格(元)')
plt.bar(x,y)
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

counts = [randint(3500,9000) for _ in range(9)]
labels = ['黄美琳{}'.format(x) for x in string.ascii_lowercase[:9]]
#距离圆心点的距离
explode = [0.1,0,0,0,0,0,0,0,0]
colors = ['red','purple','blue','yellow','gray','green']
plt.pie(counts,explode = explode,labels = labels,autopct='%1.1f%%',colors=colors)
plt.legend(loc = 2)
plt.axis('equal')
plt.show()

九、均值为 0 标准差为 1 正太分布图

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']  #解决代码中文乱码
plt.rcParams['axes.unicode_minus'] = False
import numpy as np

from random import randint
x = np.random.normal(0,1,100)
y = np.random.normal(0,1,100)
plt.scatter(x,y,alpha = 0.1)  #alpha透明度
plt.show()

十、绘制三国演义top10 饼图

◆(1) 先找出三国演义TOP10人物,分别用列表将任务名字和出现次数存起来。
◆(2)在使用plt.pie()函数绘制饼图即可。
◆代码如下:

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']  #解决代码中文乱码
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
import jieba
import string

#绘制三国演义top10 饼图
with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:
    words = f.read()
counts = {}  #{'曹操':234,'孔明':56}
excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
                "如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
                "东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
            '孔明曰','玄德曰','刘备','云长'}
words_list = jieba.lcut(words)     #精确模式

for word in words_list:
    if len(word) <= 1:
        continue
    else:
       counts[word] = counts.get(word,0) + 1

counts['孔明'] = counts['孔明'] + counts['孔明曰']
counts['玄德'] = counts['玄德'] + counts['玄德曰'] + counts['刘备']
counts['关公'] = counts['关公'] + counts['云长']
for word in excludes:
    del counts[word]

items = list(counts.items())  #字典转换成列表
def sort_by_count(x):
    return x[1]
items.sort(key = sort_by_count,reverse = True)

counthml = []
countjs = []
for i in range(10):
    #序列解包
    role,count = items[i]
    print(role, count)
    counthml.append(count)
    countjs.append(role)
#距离圆心点的距离
#explode = [0.1,0,0,0,0,0,0,0,0,0]
labels = countjs
colors = ['red','purple','blue','yellow','gray','green']
plt.pie(counthml,labels = labels,autopct='%1.1f%%')
plt.legend(loc = 2)
plt.axis('equal')
plt.show()

◆结果如下


十一、找出红楼梦TOP10人物

#红楼梦TOP10分析
import jieba

#读取小说
with open('./novel/all.txt','r',encoding='utf-8') as f:
    words = f.read()

words_list = jieba.lcut(words)

#2.分词
counts = {}
for word in words_list:
    if len(word) <= 1:
        continue
    else:
       counts[word] = counts.get(word,0) + 1
print(counts)

#3.词语过滤,删除无关词,重复词
excludes = {"什么", "一个", "我们", "你们", "如今", "说道", "老太太", "知道",
                "起来", "这里", "出来", "众人", "那里", "自己", "一面", "只见", "两个",
                "咱们", "进来", "这样", "听见", "这个", "不知", "不是", "怎么", "没有",
            '就是','东西','告诉','姑娘','老太太','太太','奶奶','回来','只是','大家',
            '凤姐儿','只得','丫头','这些','他们','不敢','出去','所以'}

counts['黛玉'] = counts['姑娘'] + counts['黛玉']
counts['贾母'] = counts['老太太'] + counts['贾母'] + counts['奶奶']
counts['王夫人'] = counts['太太'] + counts['王夫人']
counts['凤姐'] = counts['凤姐儿'] + counts['凤姐']
for word in excludes:
    del counts[word]

#4.排序[(),()]
items = list(counts.items())  # 字典转换成列表
def sort_by_count(x):
    return x[1]
items.sort(key = sort_by_count,reverse = True)


li=[]  #列表  添加 ['孔明','孔明','孔明','孔明'....,'曹操'....]
for i in range(10):
    #序列解包
    role,count = items[i]
    print(role, count)

你可能感兴趣的:(Python第三天)