国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python搜索引擎實現(xiàn)原理和方法

2020-02-16 10:52:17
字體:
供稿:網(wǎng)友

如何在龐大的數(shù)據(jù)中高效的檢索自己需要的東西?本篇內(nèi)容介紹了Python做出一個大數(shù)據(jù)搜索引擎的原理和方法,以及中間進行數(shù)據(jù)分析的原理也給大家做了詳細介紹。

布隆過濾器 (Bloom Filter)
第一步我們先要實現(xiàn)一個布隆過濾器。

布隆過濾器是大數(shù)據(jù)領(lǐng)域的一個常見算法,它的目的是過濾掉那些不是目標的元素。也就是說如果一個要搜索的詞并不存在與我的數(shù)據(jù)中,那么它可以以很快的速度返回目標不存在。

讓我們看看以下布隆過濾器的代碼:

class Bloomfilter(object):  """  A Bloom filter is a probabilistic data-structure that trades space for accuracy  when determining if a value is in a set. It can tell you if a value was possibly  added, or if it was definitely not added, but it can't tell you for certain that  it was added.  """  def __init__(self, size):    """Setup the BF with the appropriate size"""    self.values = [False] * size    self.size = size   def hash_value(self, value):    """Hash the value provided and scale it to fit the BF size"""    return hash(value) % self.size   def add_value(self, value):    """Add a value to the BF"""    h = self.hash_value(value)    self.values[h] = True   def might_contain(self, value):    """Check if the value might be in the BF"""    h = self.hash_value(value)    return self.values[h]   def print_contents(self):    """Dump the contents of the BF for debugging purposes"""    print self.values

基本的數(shù)據(jù)結(jié)構(gòu)是個數(shù)組(實際上是個位圖,用1/0來記錄數(shù)據(jù)是否存在),初始化是沒有任何內(nèi)容,所以全部置False。實際的使用當中,該數(shù)組的長度是非常大的,以保證效率。

利用哈希算法來決定數(shù)據(jù)應(yīng)該存在哪一位,也就是數(shù)組的索引

當一個數(shù)據(jù)被加入到布隆過濾器的時候,計算它的哈希值然后把相應(yīng)的位置為True

當檢查一個數(shù)據(jù)是否已經(jīng)存在或者說被索引過的時候,只要檢查對應(yīng)的哈希值所在的位的True/Fasle

看到這里,大家應(yīng)該可以看出,如果布隆過濾器返回False,那么數(shù)據(jù)一定是沒有索引過的,然而如果返回True,那也不能說數(shù)據(jù)一定就已經(jīng)被索引過。在搜索過程中使用布隆過濾器可以使得很多沒有命中的搜索提前返回來提高效率。

我們看看這段 code是如何運行的:

bf = Bloomfilter(10)bf.add_value('dog')bf.add_value('fish')bf.add_value('cat')bf.print_contents()bf.add_value('bird')bf.print_contents()# Note: contents are unchanged after adding bird - it collidesfor term in ['dog', 'fish', 'cat', 'bird', 'duck', 'emu']:print '{}: {} {}'.format(term, bf.hash_value(term), bf.might_contain(term))

結(jié)果:

[False, False, False, False, True, True, False, False, False, True][False, False, False, False, True, True, False, False, False, True]dog: 5 Truefish: 4 Truecat: 9 Truebird: 9 Trueduck: 5 Trueemu: 8 False            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 安仁县| 海南省| 广丰县| 郯城县| 濉溪县| 赫章县| 乐清市| 北海市| 黄平县| 德令哈市| 东台市| 乐安县| 临朐县| 望城县| 新田县| 高邮市| 桃园市| 庄浪县| 小金县| 淮阳县| 珲春市| 尤溪县| 安国市| 富源县| 浦城县| 剑川县| 乌拉特中旗| 来凤县| 霍城县| 驻马店市| 灵璧县| 贡觉县| 银川市| 金平| 祁门县| 寿光市| 仪征市| 黎城县| 巴彦县| 紫云| 太白县|