python学习的第三天

三国人物出场TOP10代码完善

import jieba
from wordcloud import WordCloud
import imageio
import jieba.analyse

mask = imageio.imread('./china.jpg')
#1.读取文件
with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:
    words = f.read()
    counts = {}
    excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
                "如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
                "东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
                "孔明曰","玄德曰","刘备","云长"}
    #2.分词
    words_list = jieba.lcut(words)
    for word in words_list:
        if len(word) <= 1:
            continue
        else:
            counts[word] = counts.get(word,0)+1
    #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)
    li = []
    for i in range(10):
        role,count = items[i]
        print(role)
        for _j in range(count):
            li.append(role)

    #5.结论
    text = ' '.join(li)
    wc = WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        collocations=False,
        mask=mask
    ).generate(text)
    wc.to_file('三国人物TOP10.png')
三国人物TOP10.png

利用lambda排序

#lambda x1,x2,x3....:表达式 参数可以无数多个 但是表达式只有一个
name_info_list = [
    ('张三',4500),
    ('李四',9900),
    ('王五',2000),
    ('赵六',5500),
]
name_info_list.sort(key=lambda x:x[1])
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'])
print(stu_info)
利用lambda排序.png

列表推导式,列表解析个字典解析

# 之前我们使用普通for 创建列表
li = []
for i in range(10):
    li.append(i)
print(li)
#
# # 使用列表推导式
# # [表达式 for 临时变量 in 可迭代对象 可以追加条件]
print([i for i  in range(10)])

# 列表解析
# # 筛选出列表中所有的偶数
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])

# 筛选出列表中 大于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})

matplotlib

#  导入
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np

#  使用100个点 绘制 [0 , 2π]正弦曲线图
#.linspace 左闭右闭区间的等差数列
x = np.linspace(np.pi, 2*np.pi, num=1000)
print(x)
siny = np.sin(x)
#  正弦和余弦在同一坐标系下
cosy = np.cos(x)
plt.plot(x, siny, color='g', linestyle='--',label='sin(x)')
plt.plot(x, cosy, color='r',label='cos(x)')
plt.xlabel('时间(s)')
plt.ylabel('电压(V)')
plt.title('欢迎来到python世界')
# 图例
plt.legend()
plt.show()

...
#柱状图
import string
from random import randint
x = ['口红{}'.format(x) for x in string.ascii_uppercase[:5]]
y = [randint(200,500) for _i 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, 100)
# y = np.random.normal(0, 1, 100)
# plt.scatter(x, y)
# plt.show()

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

红楼梦人物出场TOP10

from wordcloud import WordCloud
import jieba
import imageio
import jieba.analyse

#mask = imageio.imread('./china.jpg')
with open("./novel/all.txt",'r',encoding='utf-8') as f:
    words = f.read()
    counts = {}
    excludes = ['什么', '一个', '我们', '那里', '如今', '你们', '说道', '知道', '起来', '姑娘', '这里', '出来', '他们', '众人', '奶奶', '自己', '一面'
                , '只见', '怎么', '两个', '没有', '不是', '不知', '听见', '这个', '这样', '进来', '咱们', '就是', '东西', '告诉', '回来', '只是', '大家',
                '只得', '这些', '不敢', '出去', '所以', '不过', '不好', '的话', '一时', '过来', '不能', '心里', '今日', '姐姐', '太太','老太太', '丫头', '银子',
                '如此', '二人', '几个', '答应', '这么', '还有', '只管', '一回', '说话', '那边', '外头', '这话', '打发', '自然', '罢了', '今儿', '屋里','她们']
    words_list = jieba.lcut(words)
    #print(words_list)
    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['宝钗'] = counts['宝钗'] + counts['薛宝钗']
    counts['贾政'] = counts['老爷'] + counts['贾政']
    counts['王夫人'] = counts['王夫人'] + counts['太太']
    counts['凤姐'] = counts['凤姐儿'] + counts['凤姐'] + counts['王熙凤']
    for word in excludes:
        del counts[word]
    # 4.排序
    items = list(counts.items())
    items.sort(key=lambda x: x[1], reverse=True)
    li = []
    for i in range(10):
        role, count = items[i]
        print(role,count)
        for _j in range(count):
            li.append(role)

    text = ' '.join(li)
    wc = WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        collocations=False,
    ).generate(text)
    wc.to_file('红楼梦.png')
红楼梦.png

你可能感兴趣的:(python学习的第三天)