学习python的第三天

jieba实例-三国top10人物分析

步骤

1.读出小说文本
with open()as f
words=f.read()
counts={}创建空字典列表
2.分词
words_list=jieba.lcut(words)
将分词结果记录到counts列表中
for word in words_list:
if len(word) <= 1:
continue
else:
# 更新字典中的值
# counts[word] = 取出字典中原来键对应的值 + 1
# counts[word] = counts[word] + 1 # counts[word]如果没有就要报错
# 字典.get(k) 如果字典中没有这个键 返回 NONE
counts[word] = counts.get(word, 0) + 1
3.词语过滤,删除无用的词语,整合重复词
整合重复的词,比如:
counts['玄德'] = counts['玄德'] + counts['玄德曰'] +counts['刘备']
exclude={'需要删除或者过滤及重复的词'}
for word in excludes:
del counts[word]
4.排序
先遍历出字典列表,再按出场次数排序

 items = list(counts.items())
    print(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)
        # _ 是告诉看代码的人,循环里面不需要使用临时变量
        for _ in range(count):
            li.append(role)

5.得出结论
先将得出的top10人物名写入text,再按出场次数多少显示字体大小,生成top10.png

    text = ' '.join(li)
    WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        # 相邻两个重复词之间的匹配
        collocations=False
    ).generate(text).to_file('TOP10.png')

完整代码:

import jieba
# 1.读取小说内容
from wordcloud import WordCloud

with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
    words = f.read()

    counts = {}  # {‘曹操’:234,‘回寨’: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
            # counts[word] = counts[word] + 1  # counts[word]如果没有就要报错
            # 字典。get(k) 如果字典中没有这个键 返回 NONE
            counts[word] = counts.get(word, 0) + 1

    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())
    print(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)
        # _ 是告诉看代码的人,循环里面不需要使用临时变量
        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')

结果截图:

打印出人物及次数

top10

匿名函数

  • 结构
    lanmba X1,X2,·····Xn: 表达式
    参数可以无限多个,但表达式只有一个

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

  • 列表推导式
    [表达式 for 临时变量 in 可迭代对象 可以追加条件]
    举例:
# 列表解析
# # 筛选出列表中所有的偶数
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])
  • 字典解析
    举例:
# 生成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
import numpy as np
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# #  使用100个点 绘制 [0 , 2π]正弦曲线图
# #.linspace 左闭右闭区间的等差数列
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='--', 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()
正弦余弦曲线
  • 实例二柱状图
from matplotlib import pyplot as plt
import numpy as np
import string
from  random import  randint
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
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
import numpy as np
import string
from  random import  randint
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
counts = [randint(1, 100) for _ in range(7)]
print(counts)
labels = ['号码{}'.format(x) for x in string.ascii_lowercase[:7]]
explode = [0.2, 0, 0, 0, 0, 0, 0]
colors = ['red', 'purple', 'blue', 'pink', 'yellow', 'green', 'grey']
plt.pie(counts, explode=explode, shadow=True, labels=labels, colors=colors, autopct='%1.1f%%')
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)
# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
散点图

小试牛刀

1.将三国演义top10结果圆饼图展示
参考上述jieba实例,加入关键代码,如下:

    liebiao = []
    li = []  # ['孔明', 孔明, 孔明,孔明...., '曹操'。。。。。]
    for i in range(10):
        # 序列解包
        role, count = items[i]
        print(role, count)
        liebiao.append(role)
        liebiao.append(count)
        # _ 是告诉看代码的人,循环里面不需要使用临时变量
        for _ in range(count):
            li.append(role)
    print(liebiao)
        #用liebiao接收前十人物名字和次数,用分块方法取出人物名renwu和出现次数cishu
    cishu = [value for value in liebiao[1::2]]
    print(cishu)
    renwu = [value for value in liebiao[::2]]
    explode = [0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    colors = ['red', 'purple', 'blue', 'pink', 'yellow', 'green', 'grey', 'orange', 'black', 'brown']
    plt.pie(cishu, explode=explode, shadow=True, labels=renwu, colors=colors, autopct='%1.1f%%')
    plt.legend(loc=2)
    plt.axis('equal')
    plt.show()

圆饼图输出结果图:


top10圆饼
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容