您好,登錄后才能下訂單哦!
怎么在python中利用多進(jìn)程提取處理大量文本的關(guān)鍵詞?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
代碼如下:
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding("utf-8") from multiprocessing import Pool,Queue,Process import multiprocessing as mp import time,random import os import codecs import jieba.analyse jieba.analyse.set_stop_words("yy_stop_words.txt") def extract_keyword(input_string): #print("Do task by process {proc}".format(proc=os.getpid())) tags = jieba.analyse.extract_tags(input_string, topK=100) #print("key words:{kw}".format(kw=" ".join(tags))) return tags #def parallel_extract_keyword(input_string,out_file): def parallel_extract_keyword(input_string): #print("Do task by process {proc}".format(proc=os.getpid())) tags = jieba.analyse.extract_tags(input_string, topK=100) #time.sleep(random.random()) #print("key words:{kw}".format(kw=" ".join(tags))) #o_f = open(out_file,'w') #o_f.write(" ".join(tags)+"\n") return tags if __name__ == "__main__": data_file = sys.argv[1] with codecs.open(data_file) as f: lines = f.readlines() f.close() out_put = data_file.split('.')[0] +"_tags.txt" t0 = time.time() for line in lines: parallel_extract_keyword(line) #parallel_extract_keyword(line,out_put) #extract_keyword(line) print("串行處理花費(fèi)時(shí)間{t}".format(t=time.time()-t0)) pool = Pool(processes=int(mp.cpu_count()*0.7)) t1 = time.time() #for line in lines: #pool.apply_async(parallel_extract_keyword,(line,out_put)) #保存處理的結(jié)果,可以方便輸出到文件 res = pool.map(parallel_extract_keyword,lines) #print("Print keywords:") #for tag in res: #print(" ".join(tag)) pool.close() pool.join() print("并行處理花費(fèi)時(shí)間{t}s".format(t=time.time()-t1))
運(yùn)行:
python data_process_by_multiprocess.py message.txt
message.txt是每行是一個(gè)文檔,共581行,7M的數(shù)據(jù)
運(yùn)行時(shí)間:
不使用sleep來掛起進(jìn)程,也就是把time.sleep(random.random())注釋掉,運(yùn)行可以大大節(jié)省時(shí)間。
Python是一種跨平臺(tái)的、具有解釋性、編譯性、互動(dòng)性和面向?qū)ο蟮哪_本語言,其最初的設(shè)計(jì)是用于編寫自動(dòng)化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨(dú)立的項(xiàng)目和大型項(xiàng)目。
關(guān)于怎么在python中利用多進(jìn)程提取處理大量文本的關(guān)鍵詞問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。