Python 使用预定义字符分隔字符串
我有一个文本名为Python 使用预定义字符分隔字符串,python,regex,split,Python,Regex,Split,我有一个文本名为嗨,我的名字是威尔,我来自加拿大。我有两只宠物。一只是狗,另一只是斑马。啊!谢谢。 我想把这句话从和'!'中分开,我怎样才能做到这一点。我也想知道这句话是从哪个字开始的 例如,结果应为: 例1: 你好,我的名字是威尔,我来自加拿大| |这句话与 例2: Ahoi!||这句话被分成两半 我该怎么做?我迄今为止的工作: print(text.split('.')-这只会用打断句子,我无法确定它用于拆分的字符。您可以使用re.split(): 这将拆分[…]字符类中的任何字符: >
嗨,我的名字是威尔,我来自加拿大。我有两只宠物。一只是狗,另一只是斑马。啊!谢谢。
我想把这句话从
和'!'中分开,我怎样才能做到这一点。我也想知道这句话是从哪个字开始的
例如,结果应为:
例1:
你好,我的名字是威尔,我来自加拿大| |这句话与
例2:
Ahoi!||这句话被分成两半代码>
我该怎么做?我迄今为止的工作:
print(text.split('.')
-这只会用
打断句子,我无法确定它用于拆分的字符。您可以使用re.split()
:
这将拆分[…]
字符类中的任何字符:
>>> 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.']
您可以使用re.split()
:
这将拆分[…]
字符类中的任何字符:
>>> 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.']
问题是知道哪个字符用于拆分还是如何拆分句子?问题是知道哪个字符用于拆分还是如何拆分句子?如何从输出中删除None
?如何从输出中删除None