目录
1.利用jieba和词云做三国人物TOP10的词云图
2.匿名函数和列表推导式
3.正弦余弦曲线图,柱状图,饼图,散点图
内容
利用jieba和词云做三国人物TOP10的词云图
- 代码:
import imageio
import jieba
from wordcloud import WordCloud
mask = imageio.imread('./china.jpg') #背景图
with open('./novel/threekingdom.txt','r',encoding='utf-8') as f:#文档
words=f.read()
counts={}
excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
"如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
"东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
"孔明曰", "玄德曰", "刘备", "云长"}#这些是已经用分词弄出来的高频词汇
#2 分词
words_list= jieba.lcut(words)#全模式,查找words里所有可能的分词
print(words_list)#输出
for word in words_list:
if len(word)<=1:
continue
else: #统计分词个数
counts[word]=counts.get(word,0)+1
print(len(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=lambda i:i[1],reverse=True)#此处lambda是后面所学,改写的,原为'key=sort_by_count'
li=[]
for i in range(10):
role, count = items[i]
print(role, count)
# '_' 是告诉看代码的人,循环里面不需要使用临时变量
for _ in range(count):
li.append(role)
#5得出结论
text = ' '.join(li)
WordCloud(
font_path='msyh.ttc',
background_color='white',
width=800,
height=600,
# 相邻两个重复词之间的匹配
collocations=False,
mask = mask
).generate(text).to_file('TO10.png')
-
效果图:
匿名函数和列表推导式
匿名函数
- 匿名函数,就是没有名字的函数。
-表达式:lambda x1,x2.....xn
例如:
def sum_num(x1, x2):
return x1+x2
k = sum_num (1, 2)
print(k)
#匿名函数lambda
c = lambda x1, x2: x1+x2
print(c(1, 2))
上面两段代码作用一样,但是个人匿名函数lambda更简便。
列表推导式
- [表达式 for 临时变量 in 可迭代对象 可以追加条件]
#推导式
print([i for i in range(10)])
#普通循环输出
for i in range(10):
print(i)
上面两段代码作用一样,哪个简单你说了算。
正弦余弦曲线图,柱状图,饼图,散点图
正弦余弦曲线图
- 代码:
from matplotlib import pyplot as plt
#使用100个点,绘制[0,2π]正弦曲线图
import numpy as np
x = np.linspace(0, 2*np.pi, num=100)
print(x)#在控制台输出这100个点
y = np.sin(x)
plt.plot(x, y)
plt.show()#到此为止是第一个图,sin图
#正弦和余弦在同一个坐标系
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世界')
#图例
plt.legend()
plt.show()#sin和cos
图
-
运行结果:
柱状图
- 代码:
from matplotlib import pyplot as plt
import string
from random import randint
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
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()
-
运行结果:
饼图
- 代码:
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()
-
运行结果:
散点图
- 代码:
from matplotlib import pyplot as plt
import numpy as np
x = np.random.normal(0, 1, 10)
y = np.random.normal(0, 1, 10)
plt.scatter(x, y)
plt.show()
x = np.random.normal(0, 1, 10000)
y = np.random.normal(0, 1, 10000)#alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
-
运行结果: