python多进程提取处理大量文本的关键词方法

yipeiwu_com6年前Python基础

经常需要通过python代码来提取文本的关键词,用于文本分析。而实际应用中文本量又是大量的数据,如果使用单进程的话,效率会比较低,因此可以考虑使用多进程。

python的多进程只需要使用multiprocessing的模块就行,如果使用大量的进程就可以使用multiprocessing的进程池--Pool,然后不同进程处理时使用apply_async函数进行异步处理即可。

实验测试语料:message.txt中存放的581行文本,一共7M的数据,每行提取100个关键词。

代码如下:

#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("串行处理花费时间{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))
	#保存处理的结果,可以方便输出到文件
	res = pool.map(parallel_extract_keyword,lines)
	#print("Print keywords:")
	#for tag in res:
		#print(" ".join(tag))
	pool.close()
	pool.join()
	print("并行处理花费时间{t}s".format(t=time.time()-t1))

运行:

python data_process_by_multiprocess.py message.txt

message.txt是每行是一个文档,共581行,7M的数据

运行时间:

不使用sleep来挂起进程,也就是把time.sleep(random.random())注释掉,运行可以大大节省时间。

以上这篇python多进程提取处理大量文本的关键词方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3+Appium安装使用教程

Python3+Appium安装使用教程

一、安装 我们知道selenium是桌面浏览器自动化操作工具(Web Browser Automation) appium是继承selenium自动化思想旨在使手机app操作也能自动化的...

在Python中用get()方法获取字典键值的教程

 get()方法返回给定键的值。如果键不可用,则返回默认值None。 语法 以下是get()方法的语法: dict.get(key, default=None) 参数...

python 迭代器和iter()函数详解及实例

python中迭代器和iter()函数 迭代器为类序列对象提供了一个类序列的接口。python的迭代无缝地支持序列对象,而且它还允许程序员迭代非序列类型,包括用户定义的对象。迭代器用起...

Python函数参数类型及排序原理总结

这篇文章主要介绍了Python函数参数类型及排序原理总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python中函数的参数问题有...

对YOLOv3模型调用时候的python接口详解

对YOLOv3模型调用时候的python接口详解

需要注意的是:更改完源程序.c文件,需要对整个项目重新编译、make install,对已经生成的文件进行更新,类似于之前VS中在一个类中增加新函数重新编译封装dll,而python接口...