今天给大家分享的是,Python里深度/广度优先算法实现,以及url去重基本策略和编码问题。
'''
date : 2018.7.29
author : 极简XksA
goal : 深度/广度优先算法、url去重、编码
'''
# 深度优先: 根左右 遍历
# 广度优先: 层次遍历,一层一层遍历
# 深度优先: 根左右 遍历 (递归实现)
def depth_tree(tree_node):
if tree_node is not None:
print(tree_node._data)
if tree_node._left is not None:
return depth_tree(tree_node._left) # 递归遍历
if tree_node._right is not None:
return depth_tree(tree_node._right) # 递归遍历
# 广度优先: 层次遍历,一层一层遍历(队列实现)
def level_queue(root):
if root is None:
return
my_queue = []
node = root
my_queue.append(node) # 根结点入队列
while my_queue:
node = my_queue.pop(0) # 出队列
print(node.elem) # 访问结点
if node.lchild is not None:
my_queue.append(node.lchild) # 入队列
if node.rchild is not None:
my_queue.append(node.rchild) # 入队列
# 爬虫去重策略
# 1.将访问过的ur保存到数据库中
# 2.将访问过的ur保存到set中,只需要o(1)的代价就可以查询url
# 10000000*2byte*50个字符/1024/1024/1024=9G
# 3.url经过md5等方法哈希后保存到set中
# 4.用 bitmap方法,将访问过的ur通过hash函数映射到某一位
# 5. bloomfilter方法对 bitmap进行改进,多重hash函数降低冲突
(具体解释在后面的 边敲边学边记 中边学边了解)
# 字符串编码
# unicode 编码表示范围最大,但占用内存大,一般使用utf-8格式编码
# 在win下默认为 gb2312编码,在linux 下默认为 utf-8
# encode : 把unicode 编码 成其他格式编码(参数指明把字符串转换成什么格式)
# decode : 把其他格式编码成 unicode编码(参数指明原字符串是什么格式)