多进程读取文件夹统计每个文件的单词频数并写入文本
时间: 2023-06-19 19:03:38 浏览: 52
可以使用Python的multiprocessing模块来实现多进程读取文件夹,并使用collections模块来统计单词频数。具体代码如下:
```python
import os
import multiprocessing
from collections import Counter
def count_words(file_path):
with open(file_path, 'r') as f:
words = f.read().split()
return Counter(words)
def write_result(result, output_file):
with open(output_file, 'w') as f:
for word, count in result.items():
f.write(f"{word}: {count}\n")
def main(input_dir, output_file, num_processes):
pool = multiprocessing.Pool(processes=num_processes)
results = []
for dirpath, _, filenames in os.walk(input_dir):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
results.append(pool.apply_async(count_words, args=(file_path,)))
pool.close()
pool.join()
final_result = Counter()
for result in results:
final_result += result.get()
write_result(final_result, output_file)
if __name__ == '__main__':
input_dir = '/path/to/input/directory'
output_file = '/path/to/output/file'
num_processes = 4
main(input_dir, output_file, num_processes)
```
首先定义了一个`count_words`函数,用于统计单个文件的单词频数。该函数接收一个文件路径作为参数,打开文件并读取所有单词,然后使用Counter类统计每个单词出现的次数,并返回结果。
接下来定义`write_result`函数,用于将统计结果写入文件。该函数接收一个Counter对象和输出文件路径作为参数,遍历Counter对象中的每个元素,并将其写入输出文件中。
最后定义`main`函数,用于处理整个程序的流程。该函数接收三个参数:输入文件夹路径、输出文件路径和进程数。首先创建一个进程池,然后遍历输入文件夹中的所有文件,将每个文件的统计任务添加到进程池中。添加完成后关闭进程池并等待所有任务完成。最后将所有任务的统计结果合并,并将合并后的结果写入输出文件中。
在`main`函数中,可以通过修改`num_processes`参数来控制使用的进程数。建议使用与CPU核心数相同的进程数以获得最佳性能。