學(xué)習(xí)python第三天

matplotlib和numpy

#  matplotlib
#  導(dǎo)入
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np

#  使用100個(gè)點(diǎn) 繪制 [0 , 2π]正弦曲線圖
#.linspace 左閉右閉區(qū)間的等差數(shù)列
x = np.linspace(0, 2*np.pi, num=100)
print(x)
y = np.sin(x)
#  正弦和余弦在同一坐標(biāo)系下
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('時(shí)間(s)')
plt.ylabel('電壓(V)')
plt.title('歡迎來(lái)到python世界')
# 圖例
plt.legend()
plt.show()
結(jié)果
  1. 導(dǎo)入matplotlib和numpy
from matplotlib import pyplot as plt
import numpy as np

2.使用100個(gè)點(diǎn) 繪制 [0 , 2π]正弦曲線圖
linspace 左閉右閉區(qū)間的等差數(shù)列

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

3.正弦和余弦在同一坐標(biāo)系下

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('時(shí)間(s)')
plt.ylabel('電壓(V)')
plt.title('歡迎來(lái)到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('價(jià)格(元)')
plt.bar(x, y)
plt.show()
結(jié)果

1.依次產(chǎn)生五個(gè)字母

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

2.產(chǎn)生五個(gè)隨機(jī)數(shù),范圍在200-500

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

3.設(shè)置、顯示

plt.xlabel('口紅品牌') #設(shè)置橫坐標(biāo)標(biāo)識(shí)
plt.ylabel('價(jià)格(元)') #設(shè)置縱坐標(biāo)標(biāo)識(shí)
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)]
# 距離圓心點(diǎn)距離
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()
結(jié)果
  1. 依次產(chǎn)生員工abcdef并且存入labels列表中
labels = ['員工{}'.format(x) for x in string.ascii_lowercase[:6] ]
  1. 隨機(jī)產(chǎn)生月薪,范圍在3500-9000,并且存入到counts列表中
counts = [randint(3500, 9000) for _ in range(6)]

3.設(shè)置、顯示

# 距離圓心點(diǎn)距離
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()

散點(diǎn)圖

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# 均值為 0 標(biāo)準(zhǔn)差為1 的正太分布數(shù)據(jù)
x = np.random.normal(0, 1, 1000000)
y = np.random.normal(0, 1, 1000000)
# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
結(jié)果

1.設(shè)置均值、標(biāo)準(zhǔn)差

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

2.設(shè)置透明度和顯示

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

分析三國(guó)人物出現(xiàn)前十

import jieba
from wordcloud import WordCloud
# 1.讀取小說(shuō)內(nèi)容
with open('./novel/novel/threekingdom.txt', 'r', encoding='utf-8') as f:
    words = f.read()

    counts = {}  # {‘曹操’:234,‘回寨’:56}
    excludes = {"將軍", "卻說(shuō)", "丞相", "二人", "不可", "荊州", "不能", "如此", "商議",
                "如何", "主公", "軍士", "軍馬", "左右", "次日", "引兵", "大喜", "天下",
                "東吳", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人馬", "不知",
                "孔明曰","玄德曰","劉備","云長(zhǎng)"}
    # 2. 分詞
    words_list = jieba.lcut(words)
    # print(words_list)
    for word in words_list:
        if len(word) <= 1:
            continue
        else:
            # 更新字典中的值
            # counts[word] = 取出字典中原來(lái)鍵對(duì)應(yīng)的值 + 1
            # counts[word] = counts[word] + 1  # counts[word]如果沒(méi)有就要報(bào)錯(cuò)
            # 字典。get(k) 如果字典中沒(méi)有這個(gè)鍵 返回 NONE
            counts[word] = counts.get(word, 0) + 1

    print(len(counts))
    # 3. 詞語(yǔ)過(guò)濾,刪除無(wú)關(guān)詞,重復(fù)詞
    counts['孔明'] =  counts['孔明'] +  counts['孔明曰']
    counts['玄德'] = counts['玄德'] + counts['玄德曰'] +counts['劉備']
    counts['關(guān)公'] = counts['關(guān)公'] +counts['云長(zhǎng)']
    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)
        # _ 是告訴看代碼的人,循環(huán)里面不需要使用臨時(shí)變量
        # for _ in range(count):
        #     li.append(role)

    # 5得出結(jié)論

    text = ' '.join(li)
    WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        # 相鄰兩個(gè)重復(fù)詞之間的匹配
        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 = ['孔明','玄德','曹操','關(guān)公','張飛','孫權(quán)','呂布','趙云','司馬懿','周瑜']
# 距離圓心點(diǎn)距離
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()
詞云結(jié)果
餅圖結(jié)果
  1. 讀取小說(shuō)內(nèi)容
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] = 取出字典中原來(lái)鍵對(duì)應(yīng)的值 + 1
            # counts[word] = counts[word] + 1  # counts[word]如果沒(méi)有就要報(bào)錯(cuò)
            # 字典。get(k) 如果字典中沒(méi)有這個(gè)鍵 返回 NONE
            counts[word] = counts.get(word, 0) + 1
  1. 詞語(yǔ)過(guò)濾,刪除無(wú)關(guān)詞,重復(fù)詞
    counts['孔明'] =  counts['孔明'] +  counts['孔明曰']
    counts['玄德'] = counts['玄德'] + counts['玄德曰'] +counts['劉備']
    counts['關(guān)公'] = counts['關(guān)公'] +counts['云長(zhǎng)']
    for word in excludes:
        del counts[word]
  1. 排序
items = list(counts.items())
    items.sort(key=lambda x:x[1], reverse=True) # lambda表達(dá)式,可以有多個(gè)參數(shù),但是只有一個(gè)表達(dá)式
                                                 #      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)
        # _ 是告訴看代碼的人,循環(huán)里面不需要使用臨時(shí)變量
        # for _ in range(count):
        #     li.append(role)
  1. 得出結(jié)論
    5.1 詞云
    text = ' '.join(li)
    WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        # 相鄰兩個(gè)重復(fù)詞之間的匹配
        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 = ['孔明','玄德','曹操','關(guān)公','張飛','孫權(quán)','呂布','趙云','司馬懿','周瑜']
# 距離圓心點(diǎn)距離
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()

以同樣方法分析紅樓夢(mèng)人物出場(chǎng)次數(shù)前十

import jieba
from wordcloud import WordCloud
# 1.讀取小說(shuō)內(nèi)容
with open('./novel/novel/all.txt', 'r', encoding='utf-8') as f:
    words = f.read()

    counts = {}
    excludes = {"什么", "一個(gè)", "我們", "你們", "如今", "說(shuō)道", "知道", "老太太", "姑娘",
                "起來(lái)", "這里", "出來(lái)", "眾人", "那里", "奶奶", "自己", "太太", "一面",
                "只見(jiàn)", "兩個(gè)", "沒(méi)有", "怎么", "不是", "不知", "這個(gè)", "聽(tīng)見(jiàn)", "這樣",
                "進(jìn)來(lái)","咱們","就是","東西","告訴","回來(lái)","只是","大家","老爺","只得",
                "丫頭","這些","他們","不敢","出去","所以","賈母笑","鳳姐兒","不過(guò)"}
    # 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. 詞語(yǔ)過(guò)濾,刪除無(wú)關(guān)詞,重復(fù)詞
    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)
        # _ 是告訴看代碼的人,循環(huán)里面不需要使用臨時(shí)變量
        for _ in range(count):
            ll.append(role)

    # 5得出結(jié)論

    text = ' '.join(ll)
    WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        # 相鄰兩個(gè)重復(fù)詞之間的匹配
        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()
詞云結(jié)果

餅圖結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容