【问题标题】:Python - split sentence after words but with maximum of n characters in resultPython - 在单词后拆分句子,但结果中最多 n 个字符
【发布时间】:2013-09-04 07:05:43
【问题描述】:

我想在宽度为 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) 开始获取每个元素(单词、标点符号)的列表,但我无法将它们组合起来。

你能帮我,或者至少给我一些提示吗?

谢谢!

【问题讨论】:

    标签: python regex string python-2.7


    【解决方案1】:

    我会看看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']
    

    【讨论】:

    • 你太棒了!谢谢。
    【解决方案2】:

    按照 DSM 的建议,查看 textwrap。如果您更喜欢使用正则表达式,以下内容将帮助您部分了解

    In [10]: re.findall(r'.{,16}\b', text)
    Out[10]: 
    ['Hello, this is ',
     'an example of ',
     'text shown in ',
     'the scrolling ',
     'display. Bla, ',
     'bla, bla',
     '']
    

    (请注意缺少的感叹号和末尾的空字符串。)

    【讨论】:

    • 你想要我诚实的回答吗?最好不要坚持使用正则表达式 :) 不过还是谢谢你。
    • @spky: 实际上,我同意你的观点 :)
    【解决方案3】:

    使用正则表达式:

    >>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
    >>> pprint(re.findall(r'.{1,16}(?:\s+|$)', text))
    ['Hello, this is ',
     'an example of ',
     'text shown in ',
     'the scrolling ',
     'display. Bla, ',
     'bla, bla!']
    

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 2013-03-10
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多