如何在分隔符表达式上拆分字符串,同时将该分隔符留在前面的字符串上?
>>> text = "This is an example. Is it made up of more than once sentence? Yes, it is."
>>> re.split("[\.\?!] ", text)
['This is an example', 'Is it made up of more than one sentence', 'Yes, it is.']
我希望结果如此.
['This is an example.', 'Is it made up of more than one sentence?', 'Yes, it is.']
到目前为止,我只尝试了一个先行断言,但这根本没有分裂.
Ign*_*ams 11
>>> re.split("(?<=[\.\?!]) ", text)
['This is an example.', 'Is it made up of more than once sentence?', 'Yes, it is.']
关键是使用后视断言?<=.
import re
text = "This is an example.A particular case.Made up of more "\
       "than once sentence?Yes, it is.But no blank !!!That's"\
       " a problem ????Yes.I think so! :)"
for x in re.split("(?<=[\.\?!]) ", text):
    print repr(x)
print '\n'
for x in re.findall("[^.?!]*[.?!]|[^.?!]+(?=\Z)",text):
    print repr(x)
结果
"This is an example.A particular case.Made up of more than once sentence?Yes, it is.But no blank !!!That'sa problem ????Yes.I think so!"
':)'
'This is an example.'
'A particular case.'
'Made up of more than once sentence?'
'Yes, it is.'
'But no blank !'
'!'
'!'
"That's a problem ?"
'?'
'?'
'?'
'Yes.'
'I think so!'
' :)'
.
也
import re
text = "! This is an example.A particular case.Made up of more "\
       "than once sentence?Yes, it is.But no blank !!!That's"\
       " a problem ????Yes.I think so! :)"
res = re.split('([.?!])',text)
print [ ''.join(res[i:i+2]) for i in xrange(0,len(res),2) ]
给
['!', ' This is an example.', 'A particular case.', 'Made up of more than once sentence?', 'Yes, it is.', 'But no blank !', '!', '!', "That's a problem ?", '?', '?', '?', 'Yes.', 'I think so!', ' :)']
| 归档时间: | 
 | 
| 查看次数: | 2791 次 | 
| 最近记录: |