下面是一个使用Python并行地查找.txt文件中单词的示例代码:
import concurrent.futures
def find_words(filename, word):
count = 0
with open(filename, 'r') as file:
for line in file:
count += line.count(word)
return count
if __name__ == '__main__':
filename = 'text.txt' # 修改为你要查找的文件名
word = 'example' # 修改为你要查找的单词
# 使用线程池并行处理任务
with concurrent.futures.ThreadPoolExecutor() as executor:
# 获取文件大小以确定分块大小
file_size = executor.submit(lambda: sum(1 for _ in open(filename, 'r')))
chunk_size = file_size.result() // executor._max_workers
# 分块读取文件,并在不同线程中处理每个块
futures = []
with open(filename, 'r') as file:
while True:
chunk = file.readlines(chunk_size)
if not chunk:
break
future = executor.submit(find_words, chunk, word)
futures.append(future)
# 获取每个线程的结果并计算总数
total_count = sum(future.result() for future in futures)
print(f'Total count of "{word}" in "{filename}" is {total_count}.')
请注意,这个示例代码使用Python的concurrent.futures模块来实现并行处理。它使用Thread Pool Executor来创建线程池,并根据文件大小分块读取文件。然后,它在不同的线程中并行地处理每个文件块,并收集结果。最后,它计算结果的总数并打印输出。
在代码中,你需要将filename
变量修改为你要查找的.txt文件的路径和文件名。你也需要将word
变量修改为你要查找的单词。
请注意,并行处理适用于大文件和需要较长时间处理的情况。对于较小的文件和较快的处理任务,串行处理可能更快和更简单。