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

三國人物top10分析
讀取小說內(nèi)容
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
words = f.read()
分詞
words_list = jieba.lcut(words)
每個詞出現(xiàn)的次數(shù)

for word in words_list:
            if len(word) <= 1:    #如果詞的長度小于等于1不計入計算
               continue
           else:
               counts[word] = counts.get(word, 0) + 1   #詞計數(shù)器,每次出現(xiàn),該詞+1

Python 字典(Dictionary) get() 函數(shù)返回指定鍵的值,如果值不在字典中返回默認(rèn)值。

詞語過濾,刪除無關(guān)詞,重復(fù)詞

excludes = {"將軍", "卻說", "丞相", "二人", "不可", "荊州", "不能", "如此", "商議",
            "如何", "主公", "軍士", "軍馬", "左右", "次日", "引兵", "大喜", "天下",
            "東吳", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人馬", "不知",
            "孔明曰","玄德曰","劉備","云長"}
      counts['孔明'] =  counts['孔明'] +  counts['孔明曰']
      counts['玄德'] = counts['玄德'] + counts['玄德曰'] +counts['劉備']
      counts['關(guān)公'] = counts['關(guān)公'] +counts['云長']
      for word in excludes:
         del counts[word]

從counts中刪掉與excludes中相同的詞

匿名函數(shù)
結(jié)構(gòu)
lambda x1,x2,....xn:表達(dá)式
sum_num = lambda x1,x2:x1+x2
print(sum_num(2,3))
注意 參數(shù)可以是無限多個,但是表達(dá)式只有一個
實例

name_info_list = [
    ('張三',4500),
    ('李四',9900),
    ('王五',2000),
    ('趙六',5500),
]
name_info_list.sort(key=lambda x:x[1],reverse=True)
print(name_info_list)

使用列表推導(dǎo)式
[表達(dá)式 for 臨時變量 in 可迭代對象 可以追加條件]

print([i for i in range(10)])

實例

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個學(xué)生的成績
from random import randint
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() if v > 60})

圖形
正弦、余弦曲線圖

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
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('hello 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 _ 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_uppercase[: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()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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