Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

def splittext(text,minlength=15,maxlength=30): global yuyimodel 定义句末和句内标点符号 endpunc =…

  1. User

    def split_text(text,min_length=15,max_length=30): global yuyi_model # 定义句末和句内标点符号 end_punc = '。!?;\n' inner_punc = ',、:'

    # 第一步:初步分句
    sentences = re.split(f'([{end_punc}])', text)
    # 将句子和分隔符合并
    if sentences[-1] == '':
        sentences = sentences[:-1]
    sentences = [''.join(i) for i in zip(sentences[0::2], sentences[1::2] + [''])]
    
    chunks = []
    for sentence in sentences:
        # 去除首尾空白字符
        sentence = sentence.strip()
        if not sentence:
            continue
    
        # 如果句子长度在10到40之间,直接加入结果
        if min_length <= len(sentence) <= max_length:
            chunks.append(sentence)
        else:
            # 第二步:使用句内标点符号进一步分割
            tokens = re.split(f'([{inner_punc}])', sentence)
            tokens = [t for t in tokens if t != '']  # 去除空字符串
            # 将 tokens 合并成子句
            clauses = []
            i = 0
            while i < len(tokens):
                if i+1 < len(tokens):
                    clauses.append(''.join(tokens[i:i+2]))
                    i +=2
                else:
                    clauses.append(tokens[i])
                    i +=1
    
            for clause in clauses:
                clause = clause.strip()
                if not clause:
                    continue
                if len(clause) > max_length:
                    # 第三步:使用结巴分词进一步切分
                    words = jieba.lcut(clause)
                    # 将词按10到40字进行分块
                    start = 0
                    while start < len(words):
                        size = 0
                        block = []
                        while start < len(words) and size + len(words[start]) <= max_length:
                            block.append(words[start])
                            size += len(words[start])
                            start += 1
                        # 如果块的长度不足10字,尝试与后面的词合并
                        if size < min_length and start < len(words):
                            while start < len(words) and size < min_length:
                                block.append(words[start])
                                size += len(words[start])
                                start += 1
                        if block:
                            chunks.append(''.join(block))
                else:
                    chunks.append(clause)
    # 第四步:智能拼接长度小于10的块
    result = []
    i = 0
    while i < len(chunks):
        current_chunk = chunks[i]
        # 如果当前块长度在10到40之间,直接加入结果
        if min_length <= len(current_chunk) <= max_length:
            result.append(current_chunk)
            i += 1
        elif len(current_chunk) < min_length:
            merged = False
            # 计算与前一个块的语义相似度
            if result:
                prev_chunk = result[-1]
                combined_length = len(prev_chunk) + len(current_chunk)
                if combined_length <= max_length or True:  # 即使超过40也尝试合并
                    sentences = [prev_chunk, current_chunk]
                    embeddings = yuyi_model.encode(sentences)
                    sim_prev = cosine_similarity(embeddings[0], embeddings[1])
                else:
                    sim_prev = -1
            else:
                sim_prev = -1
    
            # 计算与后一个块的语义相似度
            if i +1 < len(chunks):
                next_chunk = chunks[i+1]
                combined_length = len(current_chunk) + len(next_chunk)
                if combined_length <= max_length or True:  # 即使超过40也尝试合并
                    sentences = [current_chunk, next_chunk]
                    embeddings = yuyi_model.encode(sentences)
                    sim_next = cosine_similarity(embeddings[0], embeddings[1])
                else:
                    sim_next = -1
            else:
                sim_next = -1
    
            # 比较相似度,选择更高的进行合并
            if sim_prev >= sim_next and sim_prev != -1:
                # 合并到前一个块
                result[-1] += current_chunk
            elif sim_next != -1:
                # 合并到后一个块
                combined_chunk = current_chunk + chunks[i+1]
                result.append(combined_chunk)
                i +=1  # 跳过下一个块
            else:
                # 无法合并,直接加入(可能不符合长度要求)
                result.append(current_chunk)
            i +=1
        else:
            # 理论上不会出现长度超过40的块
            # 但我们还是处理一下
            # 将当前块按40个字符切分
            start = 0
            while start < len(current_chunk):
                end = start + max_length
                result.append(current_chunk[start:end])
                start = end
            i +=1
    
    
    return result  合并到后一个块
    

    combined_chunk = current_chunk + chunks[i+1] result.append(combined_chunk) i +=1 # 跳过下一个块 这里是不是可以优化?不应该直接加入到结果中,因为合并后的块还可能小于min_length

  2. Assistant

    是的,您说得很对。当前的代码中,当我们将 current_chunk 与下一个块 chunks[i+1] 合并后,直接将 combined_chunk 添加到了结果列表 result 中,但是并没有检查合并后的 combined_chunk 的长度。如果合并后的 combined_chunk 仍然小于 min_length,那么我们就会把一个长度不足的块添加到结果中。

    为了优化这一点,我们可以在合并后再次检查 combined_chunk 的长度,如果仍然小于 min_length,就继续与后面的块合并,直到达到 min_length 或者没有更多的块可合并。

    下面是优化后的代码片段(仅展示修改的部分):

    elif sim_next != -1:
        # 合并到后一个或多个块,直到长度满足要求
        combined_chunk = current_chunk
        i += 1  # 移动到下一个块
        while len(combined_chunk) < min_length and i < len(chunks):
            combined_chunk += chunks[i]
            i += 1
        result.append(combined_chunk)
        # 注意,此时 i 已经指向下一个未处理的块,无需再增加 i
    else:
        # 无法合并,直接加入(可能不符合长度要求)
        result.append(current_chunk)
        i +=1
    

    解释:

    • 我们在合并到下一个块后,使用 while 循环继续检查合并后的 combined_chunk 是否满足 min_length 的要求。
    • 在循环中,不断地将下一个块添加到 combined_chunk 中,并增加索引 i,直到满足长度要求或没有更多的块可合并。
    • 当退出循环后,combined_chunk 已经是合并后的结果,我们将其添加到 result 中。
    • 因为在循环中我们已经更新了索引 i,所以在添加到 result 后不需要再对 i 进行额外的增加。

    这样修改后,合并后的块会确保长度至少为 min_length,避免了将长度不足的块直接添加到结果中的问题。

    完整修改后的代码(相关部分):

    # 第四步:智能拼接长度小于10的块
    result = []
    i = 0
    while i < len(chunks):
        current_chunk = chunks[i]
        # 如果当前块长度在10到40之间,直接加入结果
        if min_length <= len(current_chunk) <= max_length:
            result.append(current_chunk)
            i += 1
        elif len(current_chunk) < min_length:
            merged = False
            # 计算与前一个块的语义相似度
            if result:
                prev_chunk = result[-1]
                combined_length = len(prev_chunk) + len(current_chunk)
                if combined_length <= max_length or True:  # 即使超过40也尝试合并
                    sentences = [prev_chunk, current_chunk]
                    embeddings = yuyi_model.encode(sentences)
                    sim_prev = cosine_similarity(embeddings[0], embeddings[1])
                else:
                    sim_prev = -1
            else:
                sim_prev = -1
    
            # 计算与后一个块的语义相似度
            if i +1 < len(chunks):
                next_chunk = chunks[i+1]
                combined_length = len(current_chunk) + len(next_chunk)
                if combined_length <= max_length or True:  # 即使超过40也尝试合并
                    sentences = [current_chunk, next_chunk]
                    embeddings = yuyi_model.encode(sentences)
                    sim_next = cosine_similarity(embeddings[0], embeddings[1])
                else:
                    sim_next = -1
            else:
                sim_next = -1
    
            # 比较相似度,选择更高的进行合并
            if sim_prev >= sim_next and sim_prev != -1:
                # 合并到前一个块
                result[-1] += current_chunk
                i += 1
            elif sim_next != -1:
                # 合并到后一个或多个块,直到长度满足要求
                combined_chunk = current_chunk
                i += 1  # 移动到下一个块
                while len(combined_chunk) < min_length and i < len(chunks):
                    combined_chunk += chunks[i]
                    i += 1
                result.append(combined_chunk)
                # 注意,此时 i 已经指向下一个未处理的块,无需再增加 i
            else:
                # 无法合并,直接加入(可能不符合长度要求)
                result.append(current_chunk)
                i +=1
        else:
            # 理论上不会出现长度超过 max_length 的块
            # 但我们还是处理一下
            # 将当前块按 max_length 个字符切分
            start = 0
            while start < len(current_chunk):
                end = start + max_length
                result.append(current_chunk[start:end])
                start = end
            i +=1
    

    注意事项:

    • 在处理长度不足的块时,我们优先尝试与相邻的块合并(根据语义相似度)。
    • 当选择与后一个块合并时,我们使用 while 循环不断与后续的块合并,直到满足长度要求 min_length。
    • 为了确保索引的正确性,在循环内部更新了索引 i,并在必要时调整 i 的增量。

    希望这能帮助您优化代码!