簡體   English   中英

Python - 在單詞之后拆分句子,但結果中最多包含n個字符

[英]Python - split sentence after words but with maximum of n characters in result

我想在滾動顯示上顯示一些寬度為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!']

我開始使用regex 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']

正如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',
 '']

(注意最后丟失的感嘆號和空字符串。)

使用正則表達式:

>>> 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!']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM