作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我必须编写一个程序,通过文件夹中包含的文件搜索关键字并打印该关键字在其中使用的次数。为了减少搜索时间,我决定将文件夹分成 2 个文件夹,并让两个单独的函数并行运行,每个函数搜索不同的文件夹。
这是搜索文件的两个函数之一(另一个相同):
pathText1 = '/Papers/scripts1'
countmatch1 = 0;
matrix1 = [[]]
for filename1 in os.listdir(pathText1):
fileDir1 = pathText1 + '/' + filename1
fileText1 = open(fileDir1, "r",encoding='utf8')
content1 = fileText.read()
content1 = content1.lower()
countn1 = content1.count(keyword)
if count1 > 5:
print ('The word: ' + keyword + ' | was found ' + str(count1) + ' times in the file: ' + filename1)
countmatch1 = countmatch1 + 1
matrix1.append([filename1,count1])
print('found ' + countmatch1 + ' matches')
del matrix1[0]
return matrix1
所以,现在我有一个问题,如何实现多处理并使其有两个函数将矩阵返回到主函数。预先感谢您的帮助!
最佳答案
您应该使用共享变量。检查示例:
from multiprocessing import Process, Manager
def your_function(first_param, second_param):
# Your work here to search keywords
if __name__ == '__main__':
manager = Manager()
# shared variable
matrices = manager.list()
jobs = []
# Range defines how many times you want to call the method.
for each_process in range(3):
process = Process(target=your_function, args=(first_param, second_param))
jobs.append(process)
process.start()
for each_process in jobs:
each_process.join()
print(matrices)
另外,更详细的教程可以查看here .
关于python - 如何让两个不同的函数并行运行并在Python中返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58836051/
我是一名优秀的程序员,十分优秀!