【问题标题】:Split by regex of new line and capital letter按换行符和大写字母的正则表达式拆分
【发布时间】:2018-07-28 22:09:54
【问题描述】:

我一直在努力用 Python 中的正则表达式拆分我的字符串。

我有一个要加载的文本文件,格式为:

"Peter went to the gym; \nhe worked out for two hours \nKyle ate lunch 
 at Kate's house. Kyle went home at 9. \nSome other sentence 
 here\n\u2022Here's a bulleted line"

我想得到以下输出:

['Peter went to the gym; he worked out for two hours','Kyle ate lunch 
at Kate's house. He went home at 9.', 'Some other sentence here', 
'\u2022Here's a bulleted line']

我希望用 Python 中的新行和大写字母或项目符号来分割我的字符串。

我已经尝试解决问题的前半部分,只用一个新行和大写字母来分割我的字符串。

这是我目前所拥有的:

print re.findall(r'\n[A-Z][a-z]+',str,re.M)

这只是给了我:

[u'\nKyle', u'\nSome']

这只是第一个词。我已经尝试过该正则表达式的变体,但我不知道如何获得该行的其余部分。

我假设也按项目符号拆分,我将只包含一个 OR 正则表达式,其格式与按大写字母拆分的正则表达式相同。这是最好的方法吗?

我希望这是有道理的,如果我的问题仍然不清楚,我很抱歉。 :)

【问题讨论】:

  • 你也可以使用内置函数 str.splitlines()

标签: python regex


【解决方案1】:

你可以使用这个split函数:

>>> str = u"Peter went to the gym; \nhe worked out for two hours \nKyle ate lunch at Kate's house. Kyle went home at 9. \nSome other sentence here\n\u2022Here's a bulleted line"
>>> print re.split(u'\n(?=\u2022|[A-Z])', str)

[u'Peter went to the gym; \nhe worked out for two hours ',
 u"Kyle ate lunch at Kate's house. Kyle went home at 9. ",
 u'Some other sentence here',
 u"\u2022Here's a bulleted line"]

Code Demo

【讨论】:

    【解决方案2】:

    您可以在\n 处拆分,以大写字母或项目符号字符开头:

    import re
    s = """
    Peter went to the gym; \nhe worked out for two hours \nKyle ate lunch 
    at Kate's house. Kyle went home at 9. \nSome other sentence 
    here\n\u2022Here's a bulleted line
    """
    new_list = filter(None, re.split('\n(?=•)|\n(?=[A-Z])', s))
    

    输出:

    ['Peter went to the gym; \nhe worked out for two hours ', "Kyle ate lunch \nat Kate's house. Kyle went home at 9. ", 'Some other sentence \nhere', "•Here's a bulleted line\n"]
    

    或者,不使用项目符号字符的符号:

    new_list = filter(None, re.split('\n(?=\u2022)|\n(?=[A-Z])', s))
    

    【讨论】:

    • \n(?=[A-Z]|•)\s*\n(?=[A-Z]|•)
    • 嘿 - 谢谢你们两位超级有用的 cmets。您的 sn-p 非常适合大写字母。但是,它无法检测到子弹字符。这是我得到的输出:[u'Peter went to the gym; he worked out for two hours ', u"Kyle ate lunch \nat Kate's house. Kyle went home at 9. ", u"Some other sentence here\n\u2022Here's a bulleted line"]
    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2023-03-20
    • 2022-10-17
    相关资源
    最近更新 更多