1. 詞云WordCloud——續(xù)
①Python中使用open內(nèi)置函數(shù)進(jìn)行文件讀取
②利用函數(shù)jieba.lcut(words)進(jìn)行分詞
③過濾重復(fù)詞和無關(guān)詞
④給十個人物出現(xiàn)的次數(shù)進(jìn)行排序
⑤輸出圖片
示例一:三國TOP10人物分析
import jieba
from wordcloud import WordCloud
# 1.讀取小說內(nèi)容
with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:
words = f.read()
counts = {} #{‘曹操’:234既棺,‘回寨’:56}
excludes = {"將軍", "卻說", "丞相", "二人", "不可", "荊州", "不能", "如此", "商議",
"如何", "主公", "軍士", "軍馬", "左右", "次日", "引兵", "大喜", "天下",
"東吳", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人馬", "不知",
"孔明曰","玄德曰","劉備","云長"}
# 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[words]如果沒有就要報錯
# 字典。get(k) 如果字典中沒有這個鍵诅迷,返回NONE
counts[word] = counts.get(word, 0) + 1
print(counts)
# 3.詞語過濾,刪除無關(guān)詞屑那,重復(fù)詞
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)
items.sort(key=lambda i:i[1],reverse=True)
li = [] #['孔明','','']
# 遍歷
for i in range(10):
# 序列解包
role, count = items[i]
print(role, count)
# _ 是告訴看代碼的人哗咆,循環(huán)里面不需要臨時變量
for _ in range(count):
li.append(role)
# 5.得出結(jié)論
text = ' '.join(li)
WordCloud(
font_path='msyh.ttc',
background_color='white',
width=880,
height=600,
#兩個相鄰重復(fù)詞之間的匹配
collocations=False
).generate(text).to_file('TOP10.png')
三國人物TOP10.png
三國人物TOP10.png
示例二:紅樓夢TOP10人物分析
# 紅樓夢 top1o人物分析
import jieba
from wordcloud import WordCloud
# 1.讀取小說內(nèi)容
with open('./novel/all.txt','r',encoding='utf-8') as f:
words = f.read()
counts = {}
excludes = {'什么','我們','你們','如今','說道','知道','姑娘','起來','這里','出來','眾人','那里','奶奶',
'自己','太太','一面','只見','兩個','沒有','怎么','不是','不知','這個','聽見','這樣','進(jìn)來',
'咱們','就是','東西','告訴','回來','回來','只是','大家','老爺','只得','丫頭','這些','他們',
'不敢','出去','所以','一個','賈寶玉','王熙鳳','老太太','鳳姐兒','林黛玉','薛寶釵'}
# 2.分詞
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
print(counts)
# 3.詞語過濾重復(fù)詞
counts['寶玉'] = counts['寶玉'] + counts['賈寶玉']
counts['黛玉'] = counts['黛玉'] + counts['林黛玉']
counts['寶釵'] = counts['寶釵'] + counts['薛寶釵']
counts['賈母'] = counts['老太太'] + counts['賈母']
counts['鳳姐'] = counts['鳳姐'] + counts['王熙鳳']+ counts['鳳姐兒']
#刪除無關(guān)詞
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 i:i[1],reverse=True)
li = []
# 遍歷
for i in range(10):
# 序列解包
role, count = items[i]
print(role, count)
# _ 是告訴看代碼的人埃难,循環(huán)里面不需要臨時變量
for _ in range(count):
li.append(role)
# 5.得出結(jié)論
text = ' '.join(li)
WordCloud(
font_path='msyh.ttc',
background_color='white',
width=880,
height=600,
# 兩個相鄰重復(fù)詞之間的匹配
collocations=False
).generate(text).to_file('紅樓夢TOP10.png')
紅樓夢人物TOP10.png
紅樓夢人物TOP10.png
2. 匿名函數(shù)
表達(dá)式:calc = lambda n: n*n
print(calc(數(shù)值))
關(guān)鍵字lambda表示匿名函數(shù),冒號前面的n表示函數(shù)參數(shù),可以有多個參數(shù)。匿名函數(shù)有個限制,就是只能有一個表達(dá)式啦扬,不用寫return盛险,返回值就是該表達(dá)式的結(jié)果鹤啡。
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)
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)
image.png
3. 列表推導(dǎo)式
1. 列表解析
- 之前我們使用普通for 創(chuàng)建列表
如:
li = []
for i in range(10):
li.append(i)
print(li)
image.png
使用列表推導(dǎo)式
格式:[表達(dá)式 for 臨時變量 in 可迭代對象 可以追加條件]
# [表達(dá)式 for 臨時變量 in 可迭代對象 可以追加條件]
print([i for i in range(10)])
image.png
- 篩選出列表中所有的偶數(shù)
#篩選出列表中所有的偶數(shù)
li = []
for i in range(10):
if i%2 == 0:
li.append(i)
print(li)
image.png
使用列表解析
#篩選出列表中所有的偶數(shù)
print([i for i in range(10) if i%2 ==0])
image.png
- 篩選出列表中大于0的數(shù)
#篩選出列表中大于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])
image.png
2. 字典解析
# 生成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.items() if v > 60})
image.png
4. 圖形繪制
1. 正弦和余弦圖
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# 使用100個點抖部,繪制[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('時間(s)')
plt.ylabel('電壓(v)')
plt.title('歡迎來到Python的世界')
正弦和余弦圖.png
2. 柱狀圖
# 導(dǎo)入
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# 柱狀圖
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('價格(元)')
plt.bar(x,y)
plt.show()
柱狀圖.png
3. 餅圖
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
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]
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()
餅圖.png
4. 散點圖
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
x = np.random.normal(0, 1, 1000000)
y = np.random.normal(0, 1, 1000000)
# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
散點圖.png