【问题标题】:Splitting with RegEx in Python [duplicate]在 Python 中使用 RegEx 进行拆分 [重复]
【发布时间】:2020-01-07 13:43:19
【问题描述】:

我在 txt 文件中有第一本《哈利·波特》书籍的一些章节。我想将 txt 文件拆分为包含不同章节的列表,没有章节编号和章节名称。如何使用正则表达式做到这一点?

txt 如下所示:

Chapter one

The boy who lived

Mr. and Mrs. Dursley, ...

Chapter two

The vanishing glass

Nearly ten years had passed...

那么我希望我的列表看起来像:

['Mr. and Mrs. Dursley, ...', 'Nearly ten years had passed...']

我是正则表达式的新手,但这是我迄今为止尝试过的:

chapter_list = re.split('.*\n\nchapter.*\n\n?, text)

而且所有章节名称都不以the

开头

【问题讨论】:

  • 可能你可以使用chapter_list = [chapter.strip() for chapter in re.split(r'(?im)^Chapter +\w+(?:-\w+)?$', text) if chapter.strip()](?:-\w+)? 是支持 twenty-two 这样的词。也许您可以使用[ -] 而不是- 来留出空格而不是连字符。

标签: python regex


【解决方案1】:

应该这样做:

re.split('Chapter \w+\n'  ,string)

你可能会得到一个空元素,但如果有必要,很容易删除它。

输出:

['',
 '\nThe boy who lived\n\nMr. and Mrs. Dursley, ...\n\n',
 '\nThe vanishing glass\n\nNearly ten years had passed...']

【讨论】:

  • 谢谢!但我不希望包含章节标题。我想要这样['Mr. and Mrs. Dursley, ...', 'Nearly ten years had passed...']
  • @Kimmen 如果某些章节本身包含单词chapter 怎么办?
  • @Vicrobot 这可能是个问题,但他们没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
相关资源
最近更新 更多