Python Regex将txt文件分成段落

时间:2013-07-09 11:32:22

标签: python regex text

有没有办法使用正则表达式将txt文件分成段落?

例如,如果这是我的文本文件:

They call for you: The general who became a slave; the slave who became a gladiator; the gladiator who defied an      Emperor. Striking story.

Watch your thoughts, for they will become actions. Watch your actions, for they'll become...habits. Watch your habits for they will forge your character. Watch your character, for it will make your destiny.

我希望\ s在这里涉及但你如何决定只在正则表达式而不是空格中查找换行符?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

不要使用正则表达式,只需使用split:

 a="""1....
 2....
 3...."""
 print map(lambda x:x.strip(),a.split("\n"))

NB:

  • 我使用strip去除任何前导/尾随空格(包括Windows上的\ r)
  • 没有必要使用re.split,因为你可以拆分一个简单的字符