Split text on paragraphs where paragraph delimiters are non-standard

梦想的初衷 提交于 2020-01-01 05:34:11

问题


If I have text with standard paragraph formatting (a blank line followed by an indent) such as text 1 it's easy enough to extract the paragraphs using text.split("\n\n").

Text 1:

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet sapien velit, ac sodales   
 ante. Integer mattis eros non turpis interdum et auctor enim consectetur, etc.

      Praesent molestie suscipit bibendum. Donec justo purus, venenatis eget convallis sed, feugiat    
 vitae velit,etc.

But what if I have text with non-standard paragraph formatting such as text 2? No blank lines and variable leading whitespace.

Text 2:

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet sapien velit, ac sodales   
 ante. Integer mattis eros non turpis interdum et auctor enim consectetur, etc.
    Praesent molestie suscipit bibendum. Donec justo purus, venenatis eget convallis sed, feugiat    
 vitae velit,etc.

Since leading whitespace is common to both standard and non-standard formats I've thought about indexing on the regex match for leading whitespace and getting the paragraph breaks that way, but there has to be a more elegant way to do this.


回答1:


The regex solution you propose seems elegant enough:

re.split('\s{4,}',text)

This uses 4 consecutive whitespace chars as paragraph delimiter. You can use '\n\s{3,}' or something similar, if it fits better.



来源:https://stackoverflow.com/questions/15934248/split-text-on-paragraphs-where-paragraph-delimiters-are-non-standard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!