三国人物top10分析
读取小说内容
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
words = f.read()
分词
words_list = jieba.lcut(words)
每个词出现的次数
for word in words_list:
if len(word) <= 1: #如果词的长度小于等于1不计入计算
continue
else:
counts[word] = counts.get(word, 0) + 1 #词计数器,每次出现,该词+1
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。
词语过滤,删除无关词,重复词
excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
"如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
"东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
"孔明曰","玄德曰","刘备","云长"}
counts['孔明'] = counts['孔明'] + counts['孔明曰']
counts['玄德'] = counts['玄德'] + counts['玄德曰'] +counts['刘备']
counts['关公'] = counts['关公'] +counts['云长']
for word in excludes:
del counts[word]
从counts中删掉与excludes中相同的词
匿名函数
结构
lambda x1,x2,....xn:表达式
sum_num = lambda x1,x2:x1+x2
print(sum_num(2,3))
注意 参数可以是无限多个,但是表达式只有一个
实例
name_info_list = [
('张三',4500),
('李四',9900),
('王五',2000),
('赵六',5500),
]
name_info_list.sort(key=lambda x:x[1],reverse=True)
print(name_info_list)
使用列表推导式
[表达式 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个学生的成绩
from random import randint
stu_grades = {
'student{}'.format(i):randint(50,100) for i in range(1,101)
}
print(stu_grades)
#筛选出大于60分的学生
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()