学习python第三天

matplotlib和numpy

#  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(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()
结果
  1. 导入matplotlib和numpy
from matplotlib import pyplot as plt
import numpy as np

2.使用100个点 绘制 [0 , 2π]正弦曲线图
linspace 左闭右闭区间的等差数列

x = np.linspace(0, 2*np.pi, num=100)
print(x)
y = np.sin(x)

3.正弦和余弦在同一坐标系下

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()

柱状图

import string
from random import randint
# print(string.ascii_uppercase[0:6])
# ['A', 'B', 'C'...]
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()
结果

1.依次产生五个字母

x = ['口红{}'.format(x) for x in string.ascii_uppercase[:5] ]

2.产生五个随机数,范围在200-500

y = [randint(200, 500) for _ in range(5)]

3.设置、显示

plt.xlabel('口红品牌') #设置横坐标标识
plt.ylabel('价格(元)') #设置纵坐标标识
plt.bar(x, y) 
plt.show()

饼图

from random import randint
import string
labels = ['员工{}'.format(x) for x in string.ascii_lowercase[:6] ]
counts = [randint(3500, 9000) for _ in range(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()
结果
  1. 依次产生员工abcdef并且存入labels列表中
labels = ['员工{}'.format(x) for x in string.ascii_lowercase[:6] ]
  1. 随机产生月薪,范围在3500-9000,并且存入到counts列表中
counts = [randint(3500, 9000) for _ in range(6)]

3.设置、显示

# 距离圆心点距离
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()

散点图

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# 均值为 0 标准差为1 的正太分布数据
x = np.random.normal(0, 1, 1000000)
y = np.random.normal(0, 1, 1000000)
# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
结果

1.设置均值、标准差

x = np.random.normal(0, 1, 1000000)
y = np.random.normal(0, 1, 1000000)

2.设置透明度和显示

# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()

分析三国人物出现前十

import jieba
from wordcloud import WordCloud
# 1.读取小说内容
with open('./novel/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=lambda x:x[1], reverse=True)

    li = []  # ['孔明', 孔明, 孔明,孔明...., '曹操'。。。。。]
    lo = []
    for i in range(10):
        # 序列解包
        role, count = items[i]
        print(role, count)
        li.append(role)
        lo.append(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')

# 饼图
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
import string
from random import randint
import string
# counts = [randint(3500, 9000) for _ in range(6)]
labels = ['孔明','玄德','曹操','关公','张飞','孙权','吕布','赵云','司马懿','周瑜']
# 距离圆心点距离
explode = [0.1,0,0, 0, 0,0,0,0, 0, 0]
# colors = ['red', 'purple','blue', 'yellow','gray','green','bl']
plt.pie(lo,shadow=True,explode=explode, labels=li, autopct = '%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()
词云结果
饼图结果
  1. 读取小说内容
with open('./novel/novel/threekingdom.txt', 'r', encoding='utf-8') as f:
    words = f.read()

2.分词

    counts = {}  # {‘曹操’:234,‘回寨’:56}
    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
  1. 词语过滤,删除无关词,重复词
    counts['孔明'] =  counts['孔明'] +  counts['孔明曰']
    counts['玄德'] = counts['玄德'] + counts['玄德曰'] +counts['刘备']
    counts['关公'] = counts['关公'] +counts['云长']
    for word in excludes:
        del counts[word]
  1. 排序
items = list(counts.items())
    items.sort(key=lambda x:x[1], reverse=True) # lambda表达式,可以有多个参数,但是只有一个表达式
                                                 #      lambda x,y,z:x+y+z

    li = []  # ['孔明', 孔明, 孔明,孔明...., '曹操'。。。。。]
    lo = []
    for i in range(10):
        # 序列解包
        role, count = items[i]
        print(role, count)
        li.append(role)
        lo.append(count)
        # _ 是告诉看代码的人,循环里面不需要使用临时变量
        # for _ in range(count):
        #     li.append(role)
  1. 得出结论
    5.1 词云
    text = ' '.join(li)
    WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        # 相邻两个重复词之间的匹配
        collocations=False
    ).generate(text).to_file('TOP10.png')

5.2 饼图

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
import string
from random import randint
import string
# counts = [randint(3500, 9000) for _ in range(6)]
labels = ['孔明','玄德','曹操','关公','张飞','孙权','吕布','赵云','司马懿','周瑜']
# 距离圆心点距离
explode = [0.1,0,0, 0, 0,0,0,0, 0, 0]
# colors = ['red', 'purple','blue', 'yellow','gray','green','bl']
plt.pie(lo,shadow=True,explode=explode, labels=li, autopct = '%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()

以同样方法分析红楼梦人物出场次数前十

import jieba
from wordcloud import WordCloud
# 1.读取小说内容
with open('./novel/novel/all.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

    print(len(counts))
    # 3. 词语过滤,删除无关词,重复词
    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=lambda x:x[1], reverse=True)

    li = []
    lo = []
    ll = []
    for i in range(10):
        # 序列解包
        role, count = items[i]
        # print(role, count)
        li.append(role)
        lo.append(count)
        # print(li)
        # print(lo)
        # _ 是告诉看代码的人,循环里面不需要使用临时变量
        for _ in range(count):
            ll.append(role)

    # 5得出结论

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

# # 饼图
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
explode = [0.1,0,0, 0, 0,0,0,0, 0, 0]
plt.pie(lo,shadow=True,explode=explode, labels=li, autopct = '%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()
词云结果

饼图结果

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