parent
2398743ab9
commit
f2729b414f
@ -1,9 +0,0 @@
|
||||
|
||||
注册
|
||||
- 解耦合:通过回调函数,可以将不同部分的代码逻辑分离,降低模块之间的耦合度。
|
||||
- 主动通信:注册回调模式实现了下层模块与上层模块之间的主动通信。当下层模块发生特定事件或满足特定条件时,可以主动调用上层模块注册的回调函数,而不需要上层模块不停地轮询下层模块的状态。
|
||||
|
||||
- 异步处理:回调函数常用于异步操作的响应处理,可以在主线程之外执行耗时操作,提升程序的效率和响应速度。
|
||||
- 简化设计:在某些情况下,使用回调函数可以避免复杂的控制流设计,使代码更加简洁明了。
|
||||
|
||||
- 适应变化:随着项目的发展,需求可能会发生变化。注册回调模式使得在不影响现有代码的基础上,容易添加新功能或修改现有逻辑。
|
@ -1,6 +1,6 @@
|
||||
################ 待整理
|
||||
'''
|
||||
注册者 = 观察者
|
||||
你也可以把它看作订阅模式
|
||||
|
||||
每个组件提供注册消息接口和注册消息动作
|
||||
|
@ -1,5 +1,3 @@
|
||||
################ 待整理
|
||||
|
||||
from cppy.cp_util import *
|
||||
'''
|
||||
订阅者 = 注册者 = 观察者
|
@ -0,0 +1,2 @@
|
||||
|
||||
改造下适合跨进程系统的后台响应对象设计
|
@ -1,42 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import multiprocessing
|
||||
from collections import Counter
|
||||
from cppy.cp_util import *
|
||||
|
||||
|
||||
#
|
||||
# 多进程: 因为创建进程相比计算过程开销太大,结果最慢
|
||||
#
|
||||
stop_words = get_stopwords()
|
||||
|
||||
def process_chunk(chunk):
|
||||
# 过滤停用词
|
||||
words = [ w for w in chunk if ( not w in stop_words ) and len(w) >= 3 ]
|
||||
return Counter(words)
|
||||
|
||||
def merge_counts(counts_list):
|
||||
"""合并多个Counter对象的总和"""
|
||||
return sum(counts_list, Counter())
|
||||
|
||||
|
||||
@timing_decorator
|
||||
def main():
|
||||
# 读取文件内容,分割文件内容为多个块,每个块由一个进程处理
|
||||
chunks = get_chunks(testfilepath,1000)
|
||||
|
||||
# 使用多进程处理每个块
|
||||
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
|
||||
counts_list = pool.map(process_chunk, chunks)
|
||||
pool.close()
|
||||
pool.join()
|
||||
|
||||
# 合并计数
|
||||
total_counts = merge_counts(counts_list)
|
||||
|
||||
# 输出最高频的n个词
|
||||
print_word_freqs(total_counts.most_common(10))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
@ -0,0 +1,60 @@
|
||||
import os
|
||||
import threading
|
||||
from queue import Queue
|
||||
from collections import Counter
|
||||
import re
|
||||
|
||||
# 共享队列和词频统计器
|
||||
file_queue = Queue()
|
||||
word_counter = Counter()
|
||||
lock = threading.Lock() # 确保线程安全更新 Counter
|
||||
|
||||
# 读取文件并分词的函数
|
||||
def process_file():
|
||||
while True:
|
||||
try:
|
||||
# 从队列获取文件名,非阻塞
|
||||
file_path = file_queue.get_nowait()
|
||||
except:
|
||||
break # 队列为空,退出
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
text = f.read().lower()
|
||||
# 简单分词,移除标点
|
||||
words = re.findall(r'\b\w+\b', text)
|
||||
# 线程安全更新词频
|
||||
with lock:
|
||||
word_counter.update(words)
|
||||
except Exception as e:
|
||||
print(f"Error processing {file_path}: {e}")
|
||||
finally:
|
||||
file_queue.task_done()
|
||||
|
||||
def main():
|
||||
# 获取 data 目录下所有 .txt 文件
|
||||
data_dir = 'data'
|
||||
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith('.txt')]
|
||||
|
||||
# 将文件路径放入队列
|
||||
for file_path in files:
|
||||
file_queue.put(file_path)
|
||||
|
||||
# 创建并启动多个线程
|
||||
num_threads = 4 # 可根据需要调整线程数
|
||||
threads = []
|
||||
for _ in range(num_threads):
|
||||
t = threading.Thread(target=process_file)
|
||||
t.start()
|
||||
threads.append(t)
|
||||
|
||||
# 等待所有线程完成
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
# 输出前 10 高频词
|
||||
print("Top 10 高频词:")
|
||||
for word, count in word_counter.most_common(10):
|
||||
print(f"{word}: {count}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -0,0 +1,45 @@
|
||||
import os
|
||||
import re
|
||||
from collections import Counter
|
||||
from multiprocessing import Pool, Manager
|
||||
|
||||
def process_file(file_path, shared_counter):
|
||||
"""处理单个文件,统计词频"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
text = f.read().lower()
|
||||
# 简单分词,移除标点
|
||||
words = re.findall(r'\b\w+\b', text)
|
||||
# 更新共享 Counter
|
||||
shared_counter.update(words)
|
||||
except Exception as e:
|
||||
print(f"Error processing {file_path}: {e}")
|
||||
|
||||
def main():
|
||||
# 获取 data 目录下所有 .txt 文件
|
||||
data_dir = 'data'
|
||||
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith('.txt')]
|
||||
|
||||
# 使用 Manager 创建共享 Counter
|
||||
with Manager() as manager:
|
||||
shared_counter = manager.dict(Counter())
|
||||
|
||||
# 创建进程池
|
||||
with Pool(processes=4) as pool: # 可调整进程数
|
||||
# 分发任务给进程池
|
||||
for file_path in files:
|
||||
pool.apply_async(process_file, args=(file_path, shared_counter))
|
||||
# 关闭池并等待所有进程完成
|
||||
pool.close()
|
||||
pool.join()
|
||||
|
||||
# 转换为普通 Counter 以获取结果
|
||||
final_counter = Counter(dict(shared_counter))
|
||||
|
||||
# 输出前 10 高频词
|
||||
print("Top 10 高频词:")
|
||||
for word, count in final_counter.most_common(10):
|
||||
print(f"{word}: {count}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
Loading…
Reference in new issue