我想在宽度为 16 个字符的滚动显示屏上显示一些文本。 为了提高可读性,我想翻阅文本,但不是简单地每 16 个字符拆分一次,我宁愿在超过 16 个字符限制之前拆分单词或标点符号的每个结尾..
例子:
text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
此文本应转换为最多 16 个字符的字符串列表
result = ['Hello, this is ', 'an example of ', 'text shown in ', 'the scrolling ', 'display. Bla, ', 'bla, bla!']
我从正则表达式 re.split('(\W+)', text)
开始获取每个元素(单词、标点符号)的列表,但我无法组合它们。
你能帮我,或者至少给我一些提示吗?
谢谢!
最佳答案
我会查看 textwrap模块:
>>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
>>> from textwrap import wrap
>>> wrap(text, 16)
['Hello, this is', 'an example of', 'text shown in', 'the scrolling', 'display. Bla,', 'bla, bla!']
您可以在 TextWrapper 中使用很多选项,例如:
>>> from textwrap import TextWrapper
>>> w = TextWrapper(16, break_long_words=True)
>>> w.wrap("this_is_a_really_long_word")
['this_is_a_really', '_long_word']
>>> w = TextWrapper(16, break_long_words=False)
>>> w.wrap("this_is_a_really_long_word")
['this_is_a_really_long_word']
关于Python - 在单词后拆分句子但结果最多为 n 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551752/