import jieba
from wordcloud import WordCloud
import imageio
# 1.讀取小說內(nèi)容
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
words = f.read()
counts = {} # counts = {'姓名':出現(xiàn)頻率}
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
# 字典.get(k) 如果字典中沒有這個鍵 婴洼,(返回NONE)添加一個默認值:0
counts[word] = counts.get(word, 0) + 1
print(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=sort_by_count, reverse=True)
# 用列表解析排序
items.sort(key=lambda x: x[1], reverse=True)
# print(items)
li = [] # ['孔明', '孔明', '孔明',..., '曹操'...]
for i in range(10):
# 序列解包
role, count = items[i]
print(role, count)
# _ 是告訴看代碼的人摄职,循環(huán)里面不需要使用臨時變量
for _ in range(count):
li.append(role)
# 得出結論
# 繪制中文詞云朗鸠,在WordCloud()里面設置參數(shù)
text = ' '.join(li)
wc = WordCloud(
font_path='msyh.ttc',
background_color='white',
width=800,
height=600,
# 相鄰兩個重復詞之間的匹配婿脸,關掉
collocations=False
).generate(text)
wc.to_file('三國TOP10人物詞云.png')
三國TOP10人物詞云.png
2、匿名函數(shù) lambda
結構: lambda x1, x2, ...xn: 表達式
eg:
sum_num = lambda x1, x2: x1+x2
print(sum_num(2, 3))
# 結果:5
參數(shù)可以是無限多個宪潮,但是表達式只有一個
eg1:從大到小排序
name_info_list = [
('張三', 4500),
('李四', 9500),
('王五', 2000),
('趙六', 5500),
]
name_info_list.sort(key=lambda x: x[1], reverse=True)
print(name_info_list)
# 結果:[('李四', 9500), ('趙六', 5500), ('張三', 4500), ('王五', 2000)]
eg2:從小到大排序
stu_info = [
{"name": 'zhangsan', "age": 18},
{"name": 'lisi', "age": 30},
{"name": 'wangwu', "age": 99},
{"name": 'tianqi', "age": 3},
]
stu_info.sort(key=lambda i: i['age'])
print(stu_info)
# 結果:[{'name': 'tianqi', 'age': 3}, {'name': 'zhangsan', 'age': 18}, {'name': 'lisi', 'age': 30}, {'name': 'wangwu', 'age': 99}]
3溯警、列表推導式,列表解析和字典解析
1狡相、列表推導式
之前用普通for 創(chuàng)建列表
li = []
for i in range(10):
li.append(i)
print(li)
# 結果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用列表推導式創(chuàng)建列表
結構:[表達式 for 臨時變量 in 可迭代對象 可以追加條件]
print([i for i in range(10)])
# 結果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2梯轻、 列表解析
普通篩選出列表中所有的偶數(shù)
# 篩選出列表中所有的偶數(shù)
li = []
for i in range(10):
if i % 2 == 0:
li.append(i)
print(li)
# 結果:[0, 2, 4, 6, 8]
使用列表解析篩選偶數(shù)
print([i for i in range(10) if i % 2 == 0])
# 結果:[0, 2, 4, 6, 8]
篩選出列表中 大于0 的數(shù)
# 隨機生成(-10, 10)的10個數(shù)
from random import randint
num_list = [randint(-10, 10) for _ in range(10)]
print(num_list)
# 輸出num_list中 大于0 的數(shù)
print([i for i in num_list if i > 0])
# 結果:[-5, -1, -4, -8, -8, -1, -8, 7, 10, -4]
# [7, 10]
4、Matplotlib
導入
from matplotlib import pyplot as plt
使用100個點 繪制[0, 2π]正余弦曲線圖
from matplotlib import pyplot as plt
import numpy as np
# 處理中文亂碼
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 使用100個點 繪制[0, 2π]正弦曲線圖
# .linspace 左閉右閉區(qū)間的等差數(shù)列
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='--')
plt.plot(x, cosy, color='r')
plt.xlabel('時間(s)')
plt.ylabel('電壓(v)')
plt.title('歡迎來到python世界')
# 圖例
plt.legend()
plt.show()
結果:
image.png
柱狀圖
# 切片
# print(string.ascii_uppercase[0: 6])
# 結果:ABCDEF
# 柱狀圖
from matplotlib import pyplot as plt
# 處理中文亂碼
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = ['口紅{}'.format() 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()
結果:
image.png
餅圖
# 餅圖
from matplotlib import pyplot as plt
# 處理中文亂碼
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
from random import randint
counts = [randint(3500, 9000) for _ in range(6)]
labels = ['員工{}'.format(x) for x in string.ascii_lowercase[:6]]
# 距離圓心點距離
explode = [0.1, 0, 0, 0, 0, 0]
color = ['red', 'purple', 'blue', 'yellow', 'gray', 'green']
plt.pie(counts, explode=explode, shadow=True, labels=labels, autopct='%1.1f%%', colors=color)
plt.axis('equal')
plt.legend(loc=2)
plt.show()
結果:
image.png
散點圖
from matplotlib import pyplot as plt
import numpy as np
# 均值為 0 標準差為 1 的正態(tài)分布數(shù)據(jù)
x = np.random.normal(0, 1, 100)
y = np.random.normal(0, 1, 100)
plt.scatter(x, y)
plt.show()
結果:
image.png
有透明度的散點圖
from matplotlib import pyplot as plt
import numpy as np
x = np.random.normal(0, 1, 100)
y = np.random.normal(0, 1, 100)
# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
結果:
image.png