Python - 在单词后拆分句子但结果最多为 n 个字符

标签 python regex string python-2.7

我想在宽度为 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/

相关文章:

python - 嵌套列表,来自 bash 输出的 Python

javascript - 在 jquery 提交函数中分配全局变量并传递给正则表达式函数

javascript - 使用 RegExp 在模式中查找模式的多个实例

regex - Bash 需要测试字母数字字符串

python - 创建特定模式的两个列表的快速方法

python - 理解 python for 循环中的范围

python - 如何通过 params webapp2 python 发送字典?

python - Django ModelForm 验证不起作用

c++ - 如何在 C++ 中读取一行并用 '!!"分隔它?

java - Java将 float 字符串解析为 float 数组?