gpt4 book ai didi

python - 将没有换行符的字符串拆分为具有最大列数的行列表

转载 作者:太空狗 更新时间:2023-10-29 22:06:09 24 4
gpt4 key购买 nike

我有一个很长的字符串(多个段落),我需要将其拆分为一个行字符串列表。什么构成“线”的决定基于:

  • 行中的字符数小于或等于X(其中X是每行的固定列数_)
  • 或者,原始字符串中有一个换行符(这将强制创建一个新的“行”。

我知道我可以通过算法做到这一点,但我想知道 python 是否有可以处理这种情况的东西。它本质上是对字符串进行换行。

顺便说一下,输出行必须在单词边界处断开,而不是字符边界处。

这是一个输入和输出的例子:

输入:

"Within eight hours of Wilson's outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said.

Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, R-S.C. Wilson had worked on Spence's staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond, R-S.C."

输出:

"Within eight hours of Wilson's outburst, his"
"Democratic opponent, former-Marine Rob Miller,"
" had received nearly 3,000 individual "
"contributions raising approximately $100,000,"
" the Democratic Congressional Campaign Committee"
" said."
""
"Wilson, a conservative Republican who promotes a "
"strong national defense and reining in the size "
"of government, won a special election to the House"
" in 2001, succeeding the late Rep. Floyd Spence, "
"R-S.C. Wilson had worked on Spence's staff on "
"Capitol Hill and also had served as an intern"
" for Sen. Strom Thurmond, R-S.C."

最佳答案

编辑

您要找的是textwrap ,但这只是解决方案的一部分,而不是完整的解决方案。要考虑换行符,您需要这样做:

from textwrap import wrap
'\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()])

>>> print '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()])

Within eight hours of Wilson's outburst, his
Democratic opponent, former-Marine Rob Miller, had
received nearly 3,000 individual contributions
raising approximately $100,000, the Democratic
Congressional Campaign Committee said.

Wilson, a conservative Republican who promotes a
strong national defense and reining in the size of
government, won a special election to the House in
2001, succeeding the late Rep. Floyd Spence,
R-S.C. Wilson had worked on Spence's staff on
Capitol Hill and also had served as an intern for
Sen. Strom Thurmond

关于python - 将没有换行符的字符串拆分为具有最大列数的行列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com