溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python 中怎么利用多線程搜索txt文件內(nèi)容

發(fā)布時間:2021-07-22 17:24:44 來源:億速云 閱讀:114 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)Python 中怎么利用多線程搜索txt文件內(nèi)容,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

import threading
import os
 
class Find(threading.Thread): #搜索數(shù)據(jù)的線程類
 def __init__(self,datalist,startIndex,endIndex,searchstr,savefile): #datalist要搜索的內(nèi)容列表,startIndex列表搜索范圍的開始下標(biāo),searchstr要搜索的內(nèi)容
  threading.Thread.__init__(self)
  self.datalist=datalist #要搜索的數(shù)據(jù)的內(nèi)存地址
  self.startIndex=startIndex #開始的索引
  self.endIndex=endIndex #結(jié)束的索引
  self.seachstr=searchstr #需要搜索的數(shù)據(jù)
  self.savefile=savefile
 def run(self):
 	self.findlist=[]
 	for i in range(self.startIndex,self.endIndex):
  	line=self.datalist[i].decode("gbk","ignore") #讀取一行
  	if line.find(self.seachstr)!=-1:
  		print(self.getName(),line,end="") #搜索數(shù)據(jù)
  		self.findlist.append(line)
 	global mutex #多線程共享全局變量(全局鎖)
 	with mutex: #獲取鎖(自動釋放鎖)
 		for line in self.findlist:
 			self.savefile.write(line.encode("gbk"))
  	
 
mutex=threading.Lock() #創(chuàng)建一個鎖
savefile=open("c:\\zhaodao.txt","wb") #搜索到的內(nèi)容寫入該文件
 
path = "C:\\data1.txt" #要搜索的文件
file = open(path, "rb")
datalist = file.readlines() # 全部讀入內(nèi)存
lines=len(datalist) #所有的行數(shù)
searchstr=input("輸入要查詢的數(shù)據(jù)")
N=10 #開啟10個線程
threadlist=[] #線程列表
# 97 9 0-1000000 1000000-2000000 2000000-3000000
for i in range(0,N-1): #0,1,2,3,4,5,6,7,8 數(shù)據(jù)切割
 mythd= Find(datalist,i*(lines//(N-1)) , (i+1)*(lines//(N-1)),searchstr,savefile) # //表示整除
 mythd.start()
 threadlist.append(mythd) #添加到線程列表
 
#97 = 97//10*10=90
mylastthd= Find(datalist,lines//(N-1)*(N-1),lines,searchstr,savefile) #最后的線程搜索剩下的尾數(shù)
mylastthd.start()
threadlist.append(mylastthd) #添加到線程列表
 
for thd in threadlist: #遍歷線程列表
 thd.join()
print("finish")

關(guān)于Python 中怎么利用多線程搜索txt文件內(nèi)容就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI