19

我有一个字符串:

"""Hello. It's good to meet you.
My name is Bob."""

我正在尝试找到将其拆分为按句点和换行符划分的列表的最佳方法:

["Hello", "It's good to meet you", "My name is Bob"]

我很确定我应该使用正则表达式,但是,没有使用它们的经验,我正在努力弄清楚如何做到这一点。

4

5 回答 5

31

你不需要正则表达式。

>>> txt = """Hello. It's good to meet you.
... My name is Bob."""
>>> txt.split('.')
['Hello', " It's good to meet you", '\nMy name is Bob', '']
>>> [x for x in map(str.strip, txt.split('.')) if x]
['Hello', "It's good to meet you", 'My name is Bob']
于 2013-07-12T15:10:24.163 回答
2

对于您的示例,在点上拆分就足够了,可以选择后跟空格(并忽略空结果):

>>> s = """Hello. It's good to meet you.
... My name is Bob."""
>>> import re
>>> re.split(r"\.\s*", s)
['Hello', "It's good to meet you", 'My name is Bob', '']

在现实生活中,您必须处理Mr. Orange,Dr. GreeneGeorge W. Bush, 但是...

于 2013-07-12T15:12:54.213 回答
1
>>> s = """Hello. It's good to meet you.
... My name is Bob."""
>>> import re
>>> p = re.compile(r'[^\s\.][^\.\n]+')
>>> p.findall(s)
['Hello', "It's good to meet you", 'My name is Bob']
>>> s = "Hello. #It's good to meet you # .'"
>>> p.findall(s)
['Hello', "#It's good to meet you # "]
于 2013-07-12T15:11:57.903 回答
1

您可以使用此拆分

re.split(r"(?<!^)\s*[.\n]+\s*(?!$)", s)
于 2013-07-12T15:42:28.630 回答
0

矿:

re.findall('(?=\S)[^.\n]+(?<=\S)',su)
于 2013-07-12T17:12:07.390 回答