1. 篩選三國云詞中的人物名字TOP15
import jieba
from wordcloud import WordCloud
#1.讀取小說內(nèi)容
with open('./novel/threekingdom.txt','r', encoding='utf-8') as f:
words = f.read()
counts = {} #{'name':出現(xiàn)次數(shù),'name':出現(xiàn)
#2. 分詞
words_list = jieba.lcut(words)
print(words_list)
for word in words_list:
if len(word) <= 1:
continue
else:
# 更新字典中的值
# counts[word] = 取出字典中原來鍵對應(yīng)的值 + 1
# counts[word] = counts[word] + 1 # counts[word]如果沒有就要報(bào)錯(cuò)
# 字典款筑。get(k) 如果字典中沒有這個(gè)鍵 返回 NONE
counts[word] = counts.get(word, 0)+1
print(counts)
#3.詞語過濾棚放,刪除無關(guān)詞倦春,重復(fù)詞
#排除前15中不是人物名字的詞語
excludes={"將軍","卻說","丞相","二人","不可","荊州","孔明曰","不能","玄德曰","如此","商議","如何","主公","軍士","軍馬",
"左右","次日","引兵","大喜","天下","東吳","于是","今日","不敢","魏兵",
"陛下","都督","人馬","不知","漢中","一人","只見","眾將",
"后主", "大叫", "上馬", "此人", "先主", "太守","天子",
}
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())
print(items)
def sort_by_count(x):
return x[1]
items.sort(key=sort_by_count, reverse=True)
#取前15
li = [] # ['孔明'蜒茄, 孔明梅垄, 孔明厂捞,孔明...., '曹操'。队丝。靡馁。。机久。]
for i in range(14):
#序列解包
role, count = items[i]
print(role, 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('TOP15.png')
2. lambda表達(dá)式
lambda表達(dá)式,通常是不想費(fèi)神去命名一個(gè)函數(shù)膘盖,并且這個(gè)函數(shù)只使用一次的場合下使用胧弛,也就是指匿名函數(shù)。一個(gè)lambda表達(dá)式的參數(shù)可以是無限多個(gè)侠畔。
- 運(yùn)用示例
#示例1:使用lambda實(shí)現(xiàn)加法運(yùn)算
sum_num = lambda x1,x2 : x1+x2
print(sum_num(2,3))
#示例2:使用lambda表達(dá)式為列表排序
name_info_list =[
("張三",4500),
("李四",6800),
("王五",3000),
("趙六",5000)
]
name_info_list.sort(key=lambda x:x[1],reverse=True)
print(name_info_list)
#示例3:使用lambda表達(dá)式為列表排序
stu_info =[
{"name":"zhangsan", "age":18},
{"name":"lisi", "age":30},
{"name":"wangwu", "age":26},
{"name":"zhaoliu", "age":19}
]
stu_info.sort(key=lambda i:i["age"])
print(stu_info)
3. Python推導(dǎo)式
推導(dǎo)式(又稱解析式)结缚,是可以從一個(gè)數(shù)據(jù)序列構(gòu)建另一個(gè)新的數(shù)據(jù)序列的結(jié)構(gòu)體。
- 列表推導(dǎo)式
使用普通for循環(huán)生成列表和使用推導(dǎo)式生成列表的比較
# 創(chuàng)建列表
li = []
for i in range(10):
li.append(i)
print(li)
print([i for i in range(10)]) #使用推導(dǎo)式
# 篩選出列表中所有的偶數(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]) #使用推導(dǎo)式
# 使用推導(dǎo)式篩選出列表中 大于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])
- 字典推導(dǎo)式
# 生成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})
- 集合推導(dǎo)式
集合推導(dǎo)式類似與列表推導(dǎo)式软棺,區(qū)別在于{}红竭。
squared = {x**2 for x in [1, 1, 2]}
print(squared)
4. 數(shù)據(jù)可視化展示
Matplotlib是 Python 的繪圖庫, 它可與 NumPy 一起使用喘落。能夠創(chuàng)建多數(shù)類型的圖表茵宪,如曲線圖,散點(diǎn)圖瘦棋,柱狀圖稀火,餅圖,堆疊圖兽狭,3D 圖和地圖圖表憾股。
- 曲線圖
from matplotlib import pyplot as plt #導(dǎo)入matplotlib包
import numpy as np
#設(shè)置rc參數(shù)顯示中文標(biāo)題
#設(shè)置字體為SimHei顯示中文
plt.rcParams["font.sans-serif"] = ['SimHei']
#設(shè)置正常顯示字符
plt.rcParams['axes.unicode_minus'] = False
# 使用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)') #顏色:綠色鹿蜀;線條樣式:虛線箕慧;繪制sin曲線
plt.plot(x, cosy, color='r',label='cos(x)') #顏色:紅色服球;繪制cos曲線
plt.xlabel('時(shí)間(s)') #x軸單位
plt.ylabel('電壓(V)') #y軸單位
plt.title('歡迎來到python世界') #標(biāo)題
# 圖例
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()
- 餅圖
#餅圖
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)圖
# 散點(diǎn)圖
#均值為 0 標(biāo)準(zhǔn)差為1 的正太分布數(shù)據(jù)
x = np.random.normal(0, 1, 100)
y = np.random.normal(0, 1, 100)
# alpha透明度
plt.scatter(x, y, alpha=0.5)
plt.show()