Python中最快的搜索引擎之一:ThreadSearch(自己开发)(abccdee1)
ThreadSearch 用的是一個巧妙的方法來執行快速搜索的。它是用一個叫Thread 模塊里的concurrent.futures 的東西(這兩個東西是Python自帶的,不用下載)它能讓多個項目同時運行。這是我開發的搜索模塊程序代碼:
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這是一段測試代碼:
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的參數: 1. list:獲取搜索的列表
? ? ? ? ? ? ? ? ? ? ? ? ?2. div_num:把list分成多少段
search的參數: 1. preloaded :獲取preload處理完的列表
? ? ? ? ? ? ? ? ? ? ? ? 2. obj :獲取要搜索的字符/字符串
? ? ? ? ? ? ? ? ? ? ? ?3. exactly:獲取是否要字符/字符串要和preloaded里的某項一模一樣,原始值為False
load_examples: 是我用來隨機加載一個列表搞得,列表長度和num有關系.
P.S 你也可以把x給打印出來。但是效果。。。
?接下來,我們來測試一下它搜索的速度:
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)我們是用運行search函數之前和之后的時間差來判定速度的。
運行一下:
?可以看到,在100000個項目中搜索'a'只用了0.03秒。
但是如果用傳統方法的話。。。
你們自己試試吧,我的電腦CPU不好連加載隨機列表的時候都能紅:
?你們也可以試著把列表的長度提到1億來試一試我的這個程序,如果有點慢,就把div_num調整一下。
總結
以上是生活随笔為你收集整理的Python中最快的搜索引擎之一:ThreadSearch(自己开发)(abccdee1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 招行国外汇款
- 下一篇: 用rpa必须会用python语言_几步教