You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何实现句子按指定行数的理想均匀分割?

问题:实现Python函数将句子均匀分割为指定行数

需求是编写Python函数,将句子仅以空格为分隔符拆分为指定的n行,要求各行内容尽可能均匀分布,避免首行或末行过长,且必须严格分成指定行数(不能少于n行)。

示例场景

将句子 "Who has eaten the fresh brownies?" 分割为4行:

  • 理想结果:
Who has
eaten
the fresh
brownies?
  • 常见错误结果:
    要么行数不足且首行过长:

Who has eaten
the fresh
brownies?

要么末行过长:

who has
eaten
the
fresh brownies

用户已完成初始步骤:
```python
words = sentence.split()
total_words = len(words)
character_count = len(sentence)

但后续实现效果不佳,需要重新梳理思路。


解决建议

核心思路

要实现均匀分割,关键是合理分配每行的单词数量,同时处理无法整除的余数,避免集中分配导致某几行过长;如果追求字符长度更均匀,可结合每行的目标长度调整单词分配。

方案一:按单词数均匀分配(简单直接)

先计算每行基础单词数,将余数(无法整除的单词)分散到不同行,而非集中在开头或结尾,确保行数严格符合要求。

代码实现

def split_sentence_to_lines(sentence, n):
    words = sentence.split()
    total_words = len(words)
    
    # 边界情况处理
    if n <= 0:
        raise ValueError("行数必须大于0")
    if n >= total_words:
        return [word for word in words]
    
    # 计算每行基础单词数和需要多分配一个单词的行数
    base_words = total_words // n
    extra_lines = total_words % n
    
    lines = []
    current_idx = 0
    
    for i in range(n):
        # 前extra_lines行各多分配一个单词,剩余行取基础单词数
        take = base_words + 1 if i < extra_lines else base_words
        # 提取当前行的单词并拼接
        line = ' '.join(words[current_idx:current_idx + take])
        lines.append(line)
        current_idx += take
    
    return lines

测试示例

sentence = "Who has eaten the fresh brownies?"
result = split_sentence_to_lines(sentence, 4)
print('\n'.join(result))

输出与理想结果完全一致:

Who has
eaten
the fresh
brownies?

方案二:按字符长度优化分配(更均匀)

如果需要各行的字符长度更接近,可基于句子总长度计算每行目标长度,逐步累加单词,同时确保剩余单词能分配到剩余行数中,避免末行过长。

代码实现

def split_sentence_by_length(sentence, n):
    words = sentence.split()
    total_words = len(words)
    
    if n <= 0:
        raise ValueError("行数必须大于0")
    if n >= total_words:
        return [word for word in words]
    
    # 计算每行目标长度(原句子总长度除以行数)
    target_len = len(sentence) / n
    lines = []
    current_line = []
    current_len = 0
    
    for idx, word in enumerate(words):
        word_len = len(word)
        remaining_lines = n - len(lines) - 1
        remaining_words = total_words - idx - 1
        
        if not current_line:
            # 当前行是空的,直接加入单词
            current_line.append(word)
            current_len = word_len
        else:
            # 计算加入当前单词后的长度(含空格)
            new_len = current_len + 1 + word_len
            # 两种情况允许加入:加入后未超目标长度10%,或剩余单词必须放入当前行才能凑够行数
            if new_len <= target_len * 1.1 or remaining_words <= remaining_lines:
                current_line.append(word)
                current_len = new_len
            else:
                # 换行,保存当前行
                lines.append(' '.join(current_line))
                current_line = [word]
                current_len = word_len
    
    # 加入最后一行
    lines.append(' '.join(current_line))
    return lines

注意事项

  1. 必须处理边界情况:行数为0或负数时抛出异常;行数大于等于单词总数时,每行一个单词。
  2. 测试不同场景:短句子多行数、长句子少行数、包含超长单词的句子,确保函数稳定性。

内容的提问来源于stack exchange,提问作者Hasse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:06:06