【发布时间】:2020-05-01 14:08:20
【问题描述】:
我有以下功能:
def match_keywords(reviews_match, nlu_match, keywords_match):
for j in range(df_NLU_Reviews.shape[0]):
if((j%1000)==0):
print(j)
keywords = df_NLU_Reviews.Keywords.iloc[j]
for i in range(len(sentences)):
try:
counter=0
for keyword in keywords:
if(keyword in sentences[i]):
counter+=1
if( (len(keywords)) == counter ):
reviews_match.append(sentences[i])
nlu_match.append(df_NLU_Reviews.NLU_Review.iloc[j])
keywords_match.append(df_NLU_Reviews.Keywords.iloc[j])
sentences.remove(sentences[i])
break
except Exception as e:
print(i)
print(j)
raise e
df_match = pd.DataFrame()
df_match['Reviews'] = reviews_match
df_match['NLU'] = nlu_match
df_match['Keywords'] = keywords_match
df_match.to_pickle("Match_Reviews.pkl")
return df_match
此函数将 3 个空列表作为参数,将在函数执行期间填充。
我想使用multiprocessing.Pool 进行并行化,但我不知道该怎么做。
我试过这个:
reviews_match = []
nlu_match = []
keywords_match = []
match_list = [reviews_match, nlu_match, keywords_match]
if __name__ == '__main__':
with Pool(processes = 12) as pool:
results = pool.map(match_keywords, zip(reviews_match, nlu_match, keywords_match))
print(results)
这个:
reviews_match = []
nlu_match = []
keywords_match = []
match_list = [reviews_match, nlu_match, keywords_match]
if __name__ == '__main__':
with Pool(processes = 12) as pool:
results = pool.map(match_keywords, zip(match_list))
print(results)
还有这个:
reviews_match = []
nlu_match = []
keywords_match = []
match_list = [reviews_match, nlu_match, keywords_match]
if __name__ == '__main__':
with Pool(processes = 12) as pool:
results = pool.starmap(match_keywords, zip(reviews_match, nlu_match, keywords_match))
print(results)
但是这些都不起作用,这些方法会抛出错误或空列表作为输出。如果我像这样在没有并行化的情况下运行这个函数:
match_keywords(reviews_match, nlu_match, keywords_match)
它工作得很好。有人可以告诉我这样做的正确方法并向我解释为什么这不起作用吗?
非常感谢您
【问题讨论】:
-
一方面:您在
map()(zip 迭代器)中传递了 1 个参数,而函数match_keywords需要 3 个参数。 -
我知道,我只是在尝试机会,因为没有任何效果,我不知道该怎么做
标签: python python-3.x function multiprocessing python-multiprocessing