一缀雳、lambda表達(dá)式——匿名函數(shù)
- 定義:lambda x1, x2....xn: 表達(dá)式
- 特點(diǎn):參數(shù)可以是無(wú)限多個(gè),但是表達(dá)式只有一個(gè),即返回值
- 應(yīng)用例子
#應(yīng)用于只使用一次的函數(shù)撇他,如排序時(shí)
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)
二、列表推導(dǎo)式
- 定義:[表達(dá)式 for 臨時(shí)變量 in 可迭代對(duì)象 可以追加條件]
- 使用例子
#篩選出偶數(shù)
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)]#在-10和10之間生成10個(gè)隨機(jī)數(shù)
print(num_list)
print([i for i in num_list if i>0])
# 篩選大于 60分的所有學(xué)生
stu_grades = {'student{}'.format(i):randint(50, 100) for i in range(1, 101)}# 生成100個(gè)學(xué)生的成績(jī)
print({k: v for k, v in stu_grades.items() if v >60})
三狈蚤、使用matplotlib繪圖庫(kù)進(jìn)行圖表繪制
折線圖——plot
#使用100個(gè)點(diǎn)繪制[0,2π]正弦曲線圖
x = np.linspace(0,2*np.pi,num=100)#linspace() 左閉右閉區(qū)間的等差數(shù)列
print(x)
siny = np.sin(x)
cosy = np.cos(x)
plt.plot(x,siny,color='r',label='sin(x)',linestyle=':')
plt.plot(x,cosy,color='b',label='cos(x)')
plt.xlabel('時(shí)間/s')
plt.ylabel('電壓/V')
plt.title('welcome')
plt.legend() #圖例
plt.show()
柱狀圖——bar
import string
from random import randint
x = ['口紅{}'.format(x) for x in string.ascii_letters[:5]]
y = [randint(200,500) for _ in range(5)]
print(x)
print(y)
plt.xlabel('品牌')
plt.ylabel('銷量')
plt.title('銷量表')
plt.bar(x,y)
plt.show()
餅圖——pie
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)#loc參數(shù)指定圖例位于第幾象限
plt.axis('equal')#使圖例和圖不重疊
plt.show()
散點(diǎn)圖——scatter
均值為 0 標(biāo)準(zhǔn)差為1 的正態(tài)分布數(shù)據(jù)
x = np.random.normal(0, 1, 1000)
y = np.random.normal(0, 1, 1000)
plt.scatter(x, y, alpha=0.1)
plt.show()
四困肩、文本分析
三國(guó)演義人名詞頻分析
import jieba
from wordcloud import WordCloud
import imageio
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
with open("./novel/threekingdom.txt", "r", encoding="UTF-8") as f:
words = f.read()
counts = {}
word_list = jieba.lcut(words)
for word in word_list:
if len(word)<=1:
continue
else:
counts[word] = counts.get(word, 0) + 1
print(counts)
counts["孔明"] = counts["孔明"] + counts["孔明曰"]
counts["玄德"] = counts["玄德"] + counts["玄德曰"] + counts["劉備"]
counts["關(guān)公"] = counts["關(guān)公"] + counts["云長(zhǎng)"]
excludes = {"將軍", "卻說(shuō)", "丞相", "二人", "不可", "荊州", "不能", "如此", "商議",
"如何", "主公", "軍士", "軍馬", "左右", "次日", "引兵", "大喜", "天下",
"東吳", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人馬", "不知",
"孔明曰", "玄德曰", "劉備", "云長(zhǎng)"}
for word in excludes:
del counts[word]
#將字典轉(zhuǎn)化成元組型列表
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 _ in range(count):#_表示循環(huán)里面用不到這個(gè)臨時(shí)變量
li.append(role)
text = " ".join(li)
WordCloud(
font_path = "msyh.ttc",
background_color = 'white',
width = 800,
height = 600,
collocations = False,
mask = imageio.imread('./china.jpg')
).generate(text).to_file("TOP10.jpg")
#將詞頻前十的人名生成餅圖
name = []
times = []
for i in range(0,10):
name.append(items[i][0])
times.append(items[i][1])
print(name)
print(times)
plt.pie(times, explode=[0.3,0,0,0,0,0,0,0,0,0], shadow=True, labels=name, autopct='%1.1f%%')
plt.legend(loc=2)#loc參數(shù)指定圖例位于第幾象限
plt.axis('equal')#使圖例和圖不重疊
plt.show()
TOP10詞云
三國(guó)詞頻前十人名餅圖
紅樓夢(mèng)人名詞頻分析
#找出人名詞頻前13的人物
import jieba
from wordcloud import WordCloud
import imageio
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
with open("./novel/dreamoftheredchamber.txt", "r", encoding="UTF-8") as f:
words = f.read()
counts = {}
word_list = jieba.lcut(words)
for word in word_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['太太']
excludes = {"老太太", "什么", "一個(gè)", "我們", "你們", "如今", "說(shuō)道", "知道", "姑娘",
"起來(lái)", "這里", "出來(lái)", "眾人", "那里", "奶奶", "自己", "太太", "只見(jiàn)",
"兩個(gè)", "沒(méi)有", "怎么", "一面", "不是", "不知", "這個(gè)", "聽見(jiàn)", "這樣",
"進(jìn)來(lái)", "咱們", "就是", "東西", "告訴", "回來(lái)", "只是", "大家", "老爺",
"只得", "丫頭", "他們", "不敢", "出去", "這些", "所以", "不過(guò)", "不好",
"姐姐", "鳳姐兒", "的話", "一時(shí)", "王熙鳳", "薛寶釵", "林黛玉", "賈寶玉"}
for word in excludes:
del counts[word]
items = list(counts.items())#將字典轉(zhuǎn)化成元組型列表
items.sort(key=lambda x:x[1], reverse=True)
print(items)
li = []
for i in range(13):
role, count = items[i]
print(role, count)
for _ in range(count):#_表示循環(huán)里面用不到這個(gè)臨時(shí)變量
li.append(role)
text = " ".join(li)
WordCloud(
font_path = "msyh.ttc",
background_color = 'white',
width = 800,
height = 600,
collocations = False,
mask = imageio.imread('./china.jpg')
).generate(text).to_file("TOP13.jpg")
TOP13詞云