Skip to main content
 首页 » 编程设计

python之按新行和大写字母的正则表达式拆分

2024年09月07日39Free-Thinker

我一直在努力通过 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 正则表达式,其格式与按大写字母拆分的正则表达式相同。这是最好的方法吗?

我希望这是有道理的,如果我的问题无论如何都不清楚,我很抱歉。 :)

请您参考如下方法:

您可以使用这个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