【问题标题】:How to trim text at word boundary in Python如何在Python中修剪单词边界处的文本
【发布时间】:2013-12-28 18:46:31
【问题描述】:

我有以下文字:

敏捷的棕狐跳过懒惰的狗

我只需要获取文本的前 12 个字符(只是为了使示例简单)。前 12 个字符是“The quick br”。 Python中有没有办法去除单词边界处的文本以摆脱“br”?

【问题讨论】:

    标签: python python-2.7 text


    【解决方案1】:

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

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

    您只需获取其中的第一个元素,您就完成了......

    【讨论】:

      【解决方案2】:

      使用textwrap

      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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 2021-07-03
        • 2013-10-22
        • 2020-07-07
        • 1970-01-01
        • 2023-04-02
        相关资源
        最近更新 更多