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

Python中如何实现长字符串按单词换行且保留原有换行符?

解决DnD法术库文本单词截断问题

核心思路是保留原有段落结构,对每个段落单独做单词级换行,避免一次性处理破坏原有的分段和换行格式。

具体实现代码

import textwrap

# 原始法术文本
spell_text = """Spell: Acid Splash

Output:

Source: Player's Handbook

Conjuration cantrip

Casting Time: 1 action
Range: 60 feet
Components: V, S
Duration: Instantaneous

You hurl a bubble of acid. Choose one creature you can see within range, or choose two creatures you can see within range that are within 5 feet of each other. A target must succeed on a Dexterity saving throw or take 1d6 acid damage.

At Higher Levels. This spell’s damage increases by 1d6 when you reach 5th level (2d6), 11th level (3d6), and 17th level (4d6).

Spell Lists. Artificer, Sorcerer, Wizard"""

# 按空行拆分段落,保留原有分段结构
paragraphs = spell_text.split('\n\n')
line_width = 80  # 自定义每行宽度,按需调整

processed_paragraphs = []
for para in paragraphs:
    if para.strip():
        # 对非空段落做单词换行,保留段落内部原有格式
        wrapped = textwrap.fill(
            para,
            width=line_width,
            break_long_words=False,  # 禁止截断单词
            replace_whitespace=False  # 保留段落内的空格、换行
        )
        processed_paragraphs.append(wrapped)
    else:
        processed_paragraphs.append('')

# 重新拼接处理后的段落
final_text = '\n\n'.join(processed_paragraphs)
print(final_text)

关键参数说明

  • break_long_words=False:强制不在单词中间截断,所有换行都只会出现在单词间隙
  • replace_whitespace=False:保留段落内的原有格式(比如法术属性的每行单独显示,不会被合并成一段)

处理后效果示例

原本被截断的句子会按单词换行,比如设置line_width=60时,效果如下:

You hurl a bubble of acid. Choose one creature you can see within range,
or choose two creatures you can see within range that are within 5 feet
of each other. A target must succeed on a Dexterity saving throw or take
1d6 acid damage.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 21:05:14