【发布时间】: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()