sha*_*Hwk 0 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('.'))- 这只会打破句子.,我无法确定它用于分割的字符.
你可以使用re.split():
re.split('[.!]', text)
Run Code Online (Sandbox Code Playgroud)
这会拆分[...]字符类中的任何字符:
>>> 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', '']
Run Code Online (Sandbox Code Playgroud)
您可以对拆分表达式进行分组,以将字符包含在输出中的单独列表元素中:
>>> 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', '.', '']
Run Code Online (Sandbox Code Playgroud)
要将标点符号附加到句子上,请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.']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |