
使用该
textwrap模块(它也会在连字符处断开):
import textwraplines = textwrap.wrap(text, width, break_long_words=False)
如果您想自己编写代码,这就是我的处理方式:首先,将文本拆分为单词。从一行中的第一个单词开始,然后迭代其余单词。如果下一个单词适合当前行,则添加它,否则结束当前行并将该单词用作下一行的第一个单词。重复直到所有单词都用完。
这是一些代码:
text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words."n = 16words = 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 += " " + wordlines.append(current)
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)