我有一个很长的字符串,我想将其分成最多 X 个字符的片段。但是,仅在一个空格处(如果字符串中的某个单词长于 X 个字符,则将其放入自己的部分)。
我什至不知道如何开始做这件事……用 Python 的方式
伪代码:
declare a list
while still some string left:
take the fist X chars of the string
find the last space in that
write everything before the space to a new list entry
delete everything to the left of the space
在我编写代码之前,是否有一些 python 模块可以帮助我(我认为 pprint 不能)?
最佳答案
使用 textwrap
模块(它也会在连字符处中断):
import textwrap
lines = textwrap.wrap(text, width, break_long_words=False)
如果您想自己编写代码,我会采用以下方法:首先,将文本拆分为单词。从一行中的第一个单词开始,然后迭代剩余的单词。如果下一个单词适合当前行,则添加它,否则完成当前行并将该单词用作下一行的第一个单词。重复直到用完所有单词。
这是一些代码:
text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words."
n = 16
words = iter(text.split())
lines, current = [], next(words)
for word in words:
if len(current) + 1 + len(word) > n:
lines.append(current)
current = word
else:
current += " " + word
lines.append(current)
关于python - 将字符串拆分为最大长度 X 的片段 - 仅在空格处拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122022/