【问题标题】:Regex punctuation split [Python]正则表达式标点符号拆分 [Python]
【发布时间】:2013-11-22 13:17:26
【问题描述】:

任何人都可以帮助我使用正则表达式吗?我目前有这个:re.split(" +", line.rstrip()),用空格隔开。

我怎样才能扩展它以涵盖标点符号呢?

【问题讨论】:

    标签: python regex string split punctuation


    【解决方案1】:

    官方 Python 文档有一个很好的例子。它将拆分所有非字母数字字符(空格和标点符号)。从字面上看,\W 是所有非单词字符的字符类。注意:下划线“_”被认为是一个“单词”字符,不会成为此处拆分的一部分。

    re.split('\W+', 'Words, words, words.')
    

    更多示例请参见https://docs.python.org/3/library/re.html,搜索页面“re.split”

    【讨论】:

    • @dantdj 所以你希望它在'"* 上拆分?这个答案就是这样做的。如My name's steve 将拆分为My names steve
    • @dantdj: 要支持 Unicode properly,您可以使用 regex module。用法是一样的,只要保证pattern和string是Unicode:import regex; L = regex.split(ur"\W+", u"किशोरी")
    【解决方案2】:

    使用string.punctuation 和字符类:

    >>> from string import punctuation
    >>> r = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
    >>> r.split('dss!dfs^  #$% jjj^')
    ['dss', 'dfs', 'jjj', '']
    

    【讨论】:

    • 字。这就是我要找的
    【解决方案3】:
    import re
    st='one two,three; four-five,    six'
    
    print re.split(r'\s+|[,;.-]\s*', st)
    # ['one', 'two', 'three', 'four', 'five', 'six']
    

    【讨论】:

    • 如何将 [ 和 ] 合并到 [,;.-] 列表中
    • @O.rka 如果您有新问题,请提出新问题。但简而言之,[][,;.-]
    【解决方案4】:

    当您考虑使用正则表达式与任何标点符号进行拆分时,您应该记住\W 模式不匹配下划线(这也是一个标点符号字符)。

    因此,您可以使用

    import re
    tokens = re.split(r'[\W_]+', text)
    

    [\W_] 匹配任何 Unicode 非字母数字字符。

    由于re.split可能会在匹配出现在字符串的开头或结尾时返回空项,因此最好使用正逻辑并使用

    import re
    tokens = re.findall(r'[^\W_]+', text)
    

    [^\W_] 匹配任何 Unicode 字母数字字符。

    Python demo

    import re
    text = "!Hello, world!"
    print( re.split(r'[\W_]+', text) )
    # => ['', 'Hello', 'world', '']
    print( re.findall(r'[^\W_]+', text) )
    # => ['Hello', 'world']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多