如何在 Python 中修剪单词边界处的文本



我有以下文字:

敏捷的棕色狐狸跳过懒惰的狗

我需要得到的不超过文本的前 12 个字符(只是为了使示例简单)。前 12 个字符是"快速 br"。Python中有没有办法去除单词边界处的文本以摆脱"br"?

当然,有几种方法可以做到这一点。一种是使用文本绕排模块:

>>> import textwrap
>>> textwrap.wrap('The quick brown fox jumps over the lazy dog', 12)
['The quick', 'brown fox', 'jumps over', 'the lazy dog']

你只需接受其中的第一个元素,你就完成了......

使用文本绕行:

In [1]: import textwrap   
In [2]: s = "The quick brown fox jumps over the lazy dog"    
In [3]: textwrap.wrap(s, 12)[0]
Out[3]: 'The quick'

最新更新