|
|
|
@ -2,16 +2,23 @@ import threading
|
|
|
|
|
from collections import Counter
|
|
|
|
|
from cppy.cp_util import *
|
|
|
|
|
|
|
|
|
|
stop_words = get_stopwords()
|
|
|
|
|
|
|
|
|
|
# 定义一个函数来计算每个线程的词频
|
|
|
|
|
def count_words(start, end, text, result_index, results):
|
|
|
|
|
words = re_split( text[start:end] )
|
|
|
|
|
words = [w for w in words if not w in stop_words]
|
|
|
|
|
result = Counter(words)
|
|
|
|
|
results[result_index] = result
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
#
|
|
|
|
|
# 多线程
|
|
|
|
|
#
|
|
|
|
|
def process_chunk(start, end, text, result_index, results):
|
|
|
|
|
# 切词并过滤停用词
|
|
|
|
|
words = extract_str_words( text[start:end] )
|
|
|
|
|
results[result_index] = Counter(words)
|
|
|
|
|
|
|
|
|
|
def merge_counts(counts_list):
|
|
|
|
|
# 合并多个Counter对象
|
|
|
|
|
total_counts = Counter()
|
|
|
|
|
for counts in counts_list:
|
|
|
|
|
total_counts += counts
|
|
|
|
|
return total_counts
|
|
|
|
|
|
|
|
|
|
@timing_decorator
|
|
|
|
|
def main():
|
|
|
|
|
# 读取文件内容
|
|
|
|
|
text = read_file(testfilepath)
|
|
|
|
|
|
|
|
|
@ -29,16 +36,19 @@ if __name__ == '__main__':
|
|
|
|
|
start = i * chunk_size
|
|
|
|
|
# 确保最后一个线程能够读取文件的末尾
|
|
|
|
|
end = text_length if i == num_threads - 1 else (i + 1) * chunk_size
|
|
|
|
|
t = threading.Thread(target=count_words, args=(start, end, text, i, results))
|
|
|
|
|
t = threading.Thread(target=process_chunk, args=(start, end, text, i, results))
|
|
|
|
|
threads.append(t)
|
|
|
|
|
t.start()
|
|
|
|
|
|
|
|
|
|
# 等待所有线程完成
|
|
|
|
|
for t in threads: t.join()
|
|
|
|
|
|
|
|
|
|
# 合并结果
|
|
|
|
|
total_count = Counter()
|
|
|
|
|
for result in results: total_count += result
|
|
|
|
|
# 合并计数
|
|
|
|
|
total_counts = merge_counts(results)
|
|
|
|
|
|
|
|
|
|
# 打印词频最高的10个单词
|
|
|
|
|
print_word_freqs( total_count.most_common(10) )
|
|
|
|
|
# 输出最高频的n个词
|
|
|
|
|
print_word_freqs( total_counts.most_common(10) )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
main()
|