Python多进程并行split处理时如何实现不截断单词的字符串分块
无单词截断的文本并行分块实现
分块逻辑调整方向
原有代码按照文本总长度平均分配字符切片,属于硬切逻辑,完全不匹配文本的单词边界,因此总会出现单词被拦腰截断分给两个进程的问题。调整的核心逻辑为:
- 每个分块不直接用计算出的理论切分点作为边界,而是从理论切分点向后扫描最近的空白字符位置,用这个位置作为当前块的真实结束点,保证当前块的内容始终以完整单词收尾
- 相邻分块的起始位置对齐到上一个真实结束点的后序字符,确保分块之间没有字符重叠,也不会遗漏文本内容
- 最后一个分块的终止位置直接固定为文本末尾,不需要额外寻找边界,避免丢失文本末尾的内容
- 增加兜底逻辑:如果理论切分点之后遍历到文本末尾都没有找到空白字符(比如存在超长无间隔的异常字符串),就退回使用理论切分点,避免扫描逻辑卡住
修改后的完整代码
import concurrent.futures def split_text(text, process_id): print(process_id, "received: ", text) return text.split() def main(): text = "Lorem Ipsum is simply dummy text of the printing and " \ "typesetting industry. Lorem Ipsum has been the industry's " \ "standard dummy text ever since the 1500s, when an unknown " \ "printer took a galley of type and scrambled it to make a type " \ "specimen book. It has survived not only five centuries, but also " \ "the leap into electronic typesetting, remaining essentially unchanged. " \ "It was popularised in the 1960s with the release of Letraset sheets " \ "containing Lorem Ipsum passages, and more recently with desktop publishing " \ "software like Aldus PageMaker including versions of Lorem Ipsum" n_processes = 5 total_len = len(text) chunk_bounds = [] current_start = 0 # 预计算所有不截断单词的分块边界 for i in range(n_processes): # 最后一个块直接延伸到文本末尾 if i == n_processes - 1: chunk_bounds.append((current_start, total_len)) break # 计算当前块的理论切分点 theoretical_end = int(((i + 1) / n_processes) * total_len) # 从理论切分点向后找最近的空格,作为真实的块结束位置 actual_end = text.find(' ', theoretical_end) # 兜底:没找到空格就用理论切分点 if actual_end == -1: actual_end = theoretical_end chunk_bounds.append((current_start, actual_end)) # 下一个块从当前块结束位置的下一个字符开始,跳过空格 current_start = actual_end + 1 results = [] with concurrent.futures.ProcessPoolExecutor() as executor: for process_id, (start, end) in enumerate(chunk_bounds): chunk_text = text[start:end] results.append(executor.submit(split_text, chunk_text, process_id)) if __name__ == '__main__': main()
运行效果说明
调整后运行程序,所有进程接收到的文本片段都会以完整单词收尾,不会出现"sta""ndard"这类被截断的单词片段。原实现中被切分的"standard"会被完整划分到前一个进程的接收片段中,后续进程会从"standard"之后的完整单词开始接收内容。
内容的提问来源于stack exchange,提问作者Chariot
相关产品推荐
相关产品推荐

