日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Python中最快的搜索引擎之一:ThreadSearch(自己开发)(abccdee1)

發(fā)布時(shí)間:2024/1/8 66 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python中最快的搜索引擎之一:ThreadSearch(自己开发)(abccdee1) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

ThreadSearch 用的是一個(gè)巧妙的方法來(lái)執(zhí)行快速搜索的。它是用一個(gè)叫Thread 模塊里的concurrent.futures 的東西(這兩個(gè)東西是Python自帶的,不用下載)它能讓多個(gè)項(xiàng)目同時(shí)運(yùn)行。這是我開(kāi)發(fā)的搜索模塊程序代碼:

ThreadSearch.py

import concurrent.futures def preload(list, div_num):divided = []start_index = 0end_index = int(len(list)/div_num)for x in list:if list[start_index: end_index]:divided.append(list[start_index: end_index])start_index += int(len(list)/div_num)end_index += int(len(list)/div_num)return divided out = [] def search(pres, obj):def find(list_index):global outlist = pres[list_index]finded = [x for x in list if obj in x]out.append(finded)with concurrent.futures.ThreadPoolExecutor(max_workers=len(pres)) as executor:executor.map(find, range(len(pres)))return out

這是一段測(cè)試代碼:

Test.py

import random import time from ThreadSearch import * def load_examples(num):alphabet = list('abcdefghijklmnopqrstuvwxyz')randomone = []nn = ''for x in range(num):for x in range(26):nn += alphabet[random.randint(0, 25)]randomone.append(nn)nn = ''return randomone div_num = 10 obj = 'a' print('loading examples') a = load_examples(10000) print('loading examples finished') pres = preload(a, div_num) x = search(pres, obj) print(t2-t1)

preload的參數(shù): 1. list:獲取搜索的列表

? ? ? ? ? ? ? ? ? ? ? ? ?2. div_num:把list分成多少段

search的參數(shù): 1. preloaded :獲取preload處理完的列表

? ? ? ? ? ? ? ? ? ? ? ? 2. obj :獲取要搜索的字符/字符串

? ? ? ? ? ? ? ? ? ? ? ?3. exactly:獲取是否要字符/字符串要和preloaded里的某項(xiàng)一模一樣,原始值為False

load_examples: 是我用來(lái)隨機(jī)加載一個(gè)列表搞得,列表長(zhǎng)度和num有關(guān)系.

P.S 你也可以把x給打印出來(lái)。但是效果。。。

?接下來(lái),我們來(lái)測(cè)試一下它搜索的速度:

import random import time from ThreadSearch import * def load_examples(num):alphabet = list('abcdefghijklmnopqrstuvwxyz')randomone = []nn = ''for x in range(num):for x in range(26):nn += alphabet[random.randint(0, 25)]randomone.append(nn)nn = ''return randomone div_num = 10 obj = 'a' print('loading examples') a = load_examples(10000) print('loading examples finished') preloaded = preload(a, div_num) t1 = time.time() x = search(preloaded, obj) t2 = time.time() print(t2-t1)

我們是用運(yùn)行search函數(shù)之前和之后的時(shí)間差來(lái)判定速度的。

運(yùn)行一下:

?可以看到,在100000個(gè)項(xiàng)目中搜索'a'只用了0.03秒。

但是如果用傳統(tǒng)方法的話。。。

你們自己試試吧,我的電腦CPU不好連加載隨機(jī)列表的時(shí)候都能紅:

?你們也可以試著把列表的長(zhǎng)度提到1億來(lái)試一試我的這個(gè)程序,如果有點(diǎn)慢,就把div_num調(diào)整一下。

總結(jié)

以上是生活随笔為你收集整理的Python中最快的搜索引擎之一:ThreadSearch(自己开发)(abccdee1)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。