V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Axurez
V2EX  ›  问与答

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

  •  
  •   Axurez · 2014-10-12 15:02:59 +08:00 · 6909 次点击
    这是一个创建于 3521 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如根据中文标点。”?……!把文段分成一个句子。。。
    Python 2 里怎么实现呢?(编码好像总带来一些 bug)
    2 条回复    2014-10-12 15:10:23 +08:00
    imn1
        1
    imn1  
       2014-10-12 15:06:17 +08:00
    用正则拆分
    hahastudio
        2
    hahastudio  
       2014-10-12 15:10:23 +08:00   ❤️ 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
    ...
    我是一句话
    你问我要不要被分割
    不要啊

    >>>
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2392 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:11 · PVG 18:11 · LAX 03:11 · JFK 06:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.