python分割长文本
思路:设置切块允许的最大文本长度,先按照允许的最大文本长度切出一个chunk,然后检查chunk内部是否存在逗号、句号、感叹号、问号、空格等自然的语义分割符,若存在,在把该chunk继续切分,否则,该切块就是最终的切块。
def cut_text(full_text, max_chunk_size=510): if len(full_text) <= max_chunk_size: return [full_text] start_idx = 0 chunks = [] segment_tokens = set(list(",。!?: 、")) while start_idx < len(full_text): end_idx = start_idx + max_chunk_size while start_idx < end_idx < len(full_text) - 1 and full_text[end_idx - 1] not in segment_tokens: end_idx -= 1 if end_idx == start_idx: chunks.append(full_text[start_idx:start_idx + max_chunk_size]) start_idx += max_chunk_size else: chunks.append(full_text[start_idx:end_idx]) start_idx = end_idx return chunks
测试:
if __name__=='__main__': text='长官额个个沃尔公爵哦i金额共i归结为国界无关噢俄外交官,改为俄国【 额威威给额外而我国给' print(len(text)) texts=cut_text(text,max_chunk_size=10) for text in texts: print(f'len={len(text)},text={text}')
输出:
44 len=10,text=长官额个个沃尔公爵哦 len=10,text=i金额共i归结为国界 len=8,text=无关噢俄外交官, len=6,text=改为俄国【 len=10,text=额威威给额外而我国给
                    
                
                
            
        
浙公网安备 33010602011771号