Axurez
V2EX  ›  问与答

Python 2 里面怎么根据多个分隔符分裂字符串?

  •  
  •   Axurez · Oct 12, 2014 · 7367 views
    This topic created in 4275 days ago, the information mentioned may be changed or developed.
    比如根据中文标点。”?……!把文段分成一个句子。。。
    Python 2 里怎么实现呢?(编码好像总带来一些 bug)
    2 replies    2014-10-12 15:10:23 +08:00
    imn1
        1
    imn1  
       Oct 12, 2014
    用正则拆分
    hahastudio
        2
    hahastudio  
       Oct 12, 2014   ❤️ 3
    Google: Python split multiple delimiter
    http://stackoverflow.com/questions/1059559/python-strings-split-with-multiple-delimiters

    >>> import re
    >>> s = u"我是一句话。你问我要不要被分割?不要啊!"
    >>> print s
    我是一句话。你问我要不要被分割?不要啊!
    >>> re.split(u'。|?|!', s)
    [u'\u6211\u662f\u4e00\u53e5\u8bdd', u'\u4f60\u95ee\u6211\u8981\u4e0d\u8981\u88ab\u5206\u5272', u'\u4e0d\u8981\u554a', u'']
    >>> for sp in re.split(u'。|?|!', s):
    ... print sp
    ...
    我是一句话
    你问我要不要被分割
    不要啊

    >>>
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3101 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 10:44 · PVG 18:44 · LAX 03:44 · JFK 06:44
    ♥ Do have faith in what you're doing.