使用预定义字符分隔字符串

时间:2013-07-27 10:11:34

标签: python regex split

我的文字为Hi, my name is Will, And i am from Canada. I have 2 pets. One is a dog and the other is a Zebra. Ahoi! Thanks.

我想从.和'!'中拆分这句话,我该怎么做呢。我也想知道句子分裂的特征。

例如,结果应为:

示例1:

Hi, my name is Will, And i am from Canada || The sentence was split with .

示例2:

Ahoi! || The sentence was split with !

我该怎么做?我到目前为止的工作:

print (text.split('.')) - 这只会打破.的句子,我无法确定它用于分割的字符。

2 个答案:

答案 0 :(得分:5)

您可以使用re.split()

re.split('[.!]', text)

这会分割[...]字符类中的任何字符:

>>> import re
>>> text = 'Hi, my name is Will, And i am from Canada. I have 2 pets. One is a dog and the other is a Zebra. Ahoi! Thanks.'
>>> re.split('[.!]', text)
['Hi, my name is Will, And i am from Canada', ' I have 2 pets', ' One is a dog and the other is a Zebra', ' Ahoi', ' Thanks', '']

您可以对拆分表达式进行分组,以将字符包含在输出中的单独列表元素中:

>>> re.split('([.!])', text)
['Hi, my name is Will, And i am from Canada', '.', ' I have 2 pets', '.', ' One is a dog and the other is a Zebra', '.', ' Ahoi', '!', ' Thanks', '.', '']

要将标点符号附加到句子上,请改为使用re.findall()

>>> re.findall('[^.!]+?[.!]', text)
['Hi, my name is Will, And i am from Canada.', ' I have 2 pets.', ' One is a dog and the other is a Zebra.', ' Ahoi!', ' Thanks.']

答案 1 :(得分:0)

>>> sp=re.split('(\.)|(!)','aaa.bbb!ccc!ddd.eee')
>>> sp
['aaa', '.', None, 'bbb', None, '!', 'ccc', None, '!', 'ddd', '.', None, 'eee']
>>> sp[::3] # the result
['aaa', 'bbb', 'ccc', 'ddd', 'eee']
>>> sp[1::3] # where matches `.`
['.', None, None, '.']
>>> sp[2::3] # where matches `!`
[None, '!', '!', None]