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

三國人物出場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['關(guān)公'] = counts['關(guān)公'] +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.結(jié)論
    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....:表達(dá)式 參數(shù)可以無數(shù)多個(gè) 但是表達(dá)式只有一個(gè)
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

列表推導(dǎo)式,列表解析個(gè)字典解析

# 之前我們使用普通for 創(chuàng)建列表
li = []
for i in range(10):
    li.append(i)
print(li)
#
# # 使用列表推導(dǎo)式
# # [表達(dá)式 for 臨時(shí)變量 in 可迭代對象 可以追加條件]
print([i for i  in range(10)])

# 列表解析
# # 篩選出列表中所有的偶數(shù)
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 的數(shù)
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個(gè)學(xué)生的成績
stu_grades = {'student{}'.format(i):randint(50, 100) for i in range(1, 101)}
print(stu_grades)

# 篩選大于 60分的所有學(xué)生
print({k: v for k, v in stu_grades.items() if v >60})

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(np.pi, 2*np.pi, num=1000)
print(x)
siny = np.sin(x)
#  正弦和余弦在同一坐標(biāo)系下
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('時(shí)間(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('口紅價(jià)格')
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] ]
# 距離圓心點(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)圖
# 均值為 0 標(biāo)準(zhǔn)差為1 的正太分布數(shù)據(jù)
# 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 = ['什么', '一個(gè)', '我們', '那里', '如今', '你們', '說道', '知道', '起來', '姑娘', '這里', '出來', '他們', '眾人', '奶奶', '自己', '一面'
                , '只見', '怎么', '兩個(gè)', '沒有', '不是', '不知', '聽見', '這個(gè)', '這樣', '進(jìn)來', '咱們', '就是', '東西', '告訴', '回來', '只是', '大家',
                '只得', '這些', '不敢', '出去', '所以', '不過', '不好', '的話', '一時(shí)', '過來', '不能', '心里', '今日', '姐姐', '太太','老太太', '丫頭', '銀子',
                '如此', '二人', '幾個(gè)', '答應(yīng)', '這么', '還有', '只管', '一回', '說話', '那邊', '外頭', '這話', '打發(fā)', '自然', '罷了', '今兒', '屋里','她們']
    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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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