Python爬虫(二)——豆瓣图书决策树构建

简介: Matplotlib绘制决策树代码: 1 # coding=utf-8 2 import matplotlib.

Matplotlib绘制决策树代码:

 1 # coding=utf-8
 2 import matplotlib.pyplot as plt
 3 
 4 decisionNode = dict(boxstyle='sawtooth', fc='10')
 5 leafNode = dict(boxstyle='round4',fc='0.8')
 6 arrow_args = dict(arrowstyle='<-')
 7 
 8 
 9 
10 def plotNode(nodeTxt, centerPt, parentPt, nodeType):
11     createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',\
12                              xytext=centerPt,textcoords='axes fraction',\
13                              va='center', ha='center',bbox=nodeType,arrowprops\
14                              =arrow_args)
15 
16 
17 def getNumLeafs(myTree):
18     numLeafs = 0
19     firstStr = list(myTree.keys())[0]
20     secondDict = myTree[firstStr]
21     for key in secondDict:
22         if(type(secondDict[key]).__name__ == 'dict'):
23             numLeafs += getNumLeafs(secondDict[key])
24         else:
25             numLeafs += 1
26     return  numLeafs
27 
28 def getTreeDepth(myTree):
29     maxDepth = 0
30     firstStr = list(myTree.keys())[0]
31     secondDict = myTree[firstStr]
32     for key in secondDict:
33         if(type(secondDict[key]).__name__ == 'dict'):
34             thisDepth = 1+getTreeDepth((secondDict[key]))
35         else:
36             thisDepth = 1
37         if thisDepth > maxDepth: maxDepth = thisDepth
38     return maxDepth
39 
40 def retrieveTree(i):
41     #预先设置树的信息
42     listOfTree = [{
  'no surfacing':{0:'no',1:{
  'flipper':{0:'no',1:'yes'}}}},
43         {
  'no surfacing':{0:'no',1:{
  'flipper':{0:{
  'head':{0:'no',1:'yes'}},1:'no'}}}},
44         {
  'Comment score greater than 8.0':{0:{
  'Comment score greater than 9.5':{0:'Yes',1:{
  'More than 45,000 people commented': {
45         0: 'Yes',1: 'No'}}}},1:'No'}}]
46     return listOfTree[i]
47 
48 def createPlot(inTree):
49     fig = plt.figure(1,facecolor='white')
50     fig.clf()
51     axprops = dict(xticks = [], yticks=[])
52     createPlot.ax1 = plt.subplot(111,frameon = False,**axprops)
53     plotTree.totalW = float(getNumLeafs(inTree))
54     plotTree.totalD = float(getTreeDepth(inTree))
55     plotTree.xOff = -0.5/plotTree.totalW;plotTree.yOff = 1.0
56     plotTree(inTree,(0.5,1.0), '')
57     plt.title('Douban reading Decision Tree\n')
58     plt.show()
59 
60 def plotMidText(cntrPt, parentPt,txtString):
61     xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
62     yMid = (parentPt[1] - cntrPt[1])/2.0 + cntrPt[1]
63     createPlot.ax1.text(xMid, yMid, txtString)
64 
65 def plotTree(myTree, parentPt, nodeTxt):
66     numLeafs = getNumLeafs(myTree)
67     depth = getTreeDepth(myTree)
68     firstStr = list(myTree.keys())[0]
69     cntrPt = (plotTree.xOff+(1.0+float(numLeafs))/2.0/plotTree.totalW,\
70               plotTree.yOff)
71     plotMidText(cntrPt,parentPt,nodeTxt)
72     plotNode(firstStr,cntrPt,parentPt,decisionNode)
73     secondDict = myTree[firstStr]
74     plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
75     for key in secondDict:
76         if type(secondDict[key]).__name__ == 'dict':
77             plotTree(secondDict[key],cntrPt,str(key))
78         else:
79             plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
80             plotNode(secondDict[key],(plotTree.xOff,plotTree.yOff),\
81                      cntrPt,leafNode)
82             plotMidText((plotTree.xOff,plotTree.yOff),cntrPt,str(key))
83     plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
84 
85 if __name__ == '__main__':
86     myTree = retrieveTree(2)
87     createPlot(myTree)

 

 运行结果:

 

 

目录
相关文章
|
数据采集 Web App开发 数据安全/隐私保护
实战:Python爬虫如何模拟登录与维持会话状态
实战:Python爬虫如何模拟登录与维持会话状态
|
数据采集 监控 数据库
Python异步编程实战:爬虫案例
🌟 蒋星熠Jaxonic,代码为舟的星际旅人。从回调地狱到async/await协程天堂,亲历Python异步编程演进。分享高性能爬虫、数据库异步操作、限流监控等实战经验,助你驾驭并发,在二进制星河中谱写极客诗篇。
1027 3
Python异步编程实战:爬虫案例
|
数据采集 存储 XML
Python爬虫技术:从基础到实战的完整教程
最后强调: 父母法律法规限制下进行网络抓取活动; 不得侵犯他人版权隐私利益; 同时也要注意个人安全防止泄露敏感信息.
1360 19
|
数据采集 存储 JSON
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
|
数据采集 存储 JavaScript
解析Python爬虫中的Cookies和Session管理
Cookies与Session是Python爬虫中实现状态保持的核心。Cookies由服务器发送、客户端存储,用于标识用户;Session则通过唯一ID在服务端记录会话信息。二者协同实现登录模拟与数据持久化。
|
数据采集 测试技术 C++
无headers爬虫 vs 带headers爬虫:Python性能对比
无headers爬虫 vs 带headers爬虫:Python性能对比
|
数据采集 存储 JSON
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第27天】本文介绍了Python网络爬虫Scrapy框架的实战应用与技巧。首先讲解了如何创建Scrapy项目、定义爬虫、处理JSON响应、设置User-Agent和代理,以及存储爬取的数据。通过具体示例,帮助读者掌握Scrapy的核心功能和使用方法,提升数据采集效率。
834 6
|
机器学习/深度学习 数据采集 数据可视化
基于爬虫和机器学习的招聘数据分析与可视化系统,python django框架,前端bootstrap,机器学习有八种带有可视化大屏和后台
本文介绍了一个基于Python Django框架和Bootstrap前端技术,集成了机器学习算法和数据可视化的招聘数据分析与可视化系统,该系统通过爬虫技术获取职位信息,并使用多种机器学习模型进行薪资预测、职位匹配和趋势分析,提供了一个直观的可视化大屏和后台管理系统,以优化招聘策略并提升决策质量。
1448 4
|
数据采集 存储 搜索推荐
打造个性化网页爬虫:从零开始的Python教程
【8月更文挑战第31天】在数字信息的海洋中,网页爬虫是一艘能够自动搜集网络数据的神奇船只。本文将引导你启航,用Python语言建造属于你自己的网页爬虫。我们将一起探索如何从无到有,一步步构建一个能够抓取、解析并存储网页数据的基础爬虫。文章不仅分享代码,更带你理解背后的逻辑,让你能在遇到问题时自行找到解决方案。无论你是编程新手还是有一定基础的开发者,这篇文章都会为你打开一扇通往数据世界的新窗。
|
数据采集 存储 监控
Python 原生爬虫教程:网络爬虫的基本概念和认知
网络爬虫是一种自动抓取互联网信息的程序,广泛应用于搜索引擎、数据采集、新闻聚合和价格监控等领域。其工作流程包括 URL 调度、HTTP 请求、页面下载、解析、数据存储及新 URL 发现。Python 因其丰富的库(如 requests、BeautifulSoup、Scrapy)和简洁语法成为爬虫开发的首选语言。然而,在使用爬虫时需注意法律与道德问题,例如遵守 robots.txt 规则、控制请求频率以及合法使用数据,以确保爬虫技术健康有序发展。
1830 31

推荐镜像

更多