【问题标题】:Split string on punctuation or number in Python在Python中的标点符号或数字上拆分字符串
【发布时间】:2019-12-21 00:13:24
【问题描述】:

每次遇到标点符号或数字时,我都会尝试拆分字符串,例如:

toSplit = 'I2eat!Apples22becauseilike?Them'
result = re.sub('[0123456789,.?:;~!@#$%^&*()]', ' \1',toSplit).split()

期望的输出是:

['I', '2', 'eat', '!', 'Apples', '22', 'becauseilike', '?', 'Them']

但是,上面的代码(尽管它正确地分割了它应该在的地方)删除了所有的数字和标点符号。

任何澄清将不胜感激。

【问题讨论】:

  • 试试re.findall(r'\d+|[^\w\s]|_|[^\W\d_]+', toSplit)
  • 那么,如果有像11!!这样的字符串,你需要得到['11', '!!'],对吧?
  • 是的,没错。我还没有尝试过这种情况,谢谢指出:)
  • 然后您可以使用re.findall(r'\d+|(?:[^\w\s]|_)+|[^\W\d_]+', toSplit) 将解决方案概括为数字、字母和其他不是空格、字母和数字的字符。我想知道你还想用22.45text?!做什么...

标签: python regex split numbers punctuation


【解决方案1】:

re.split 与捕获组一起使用:

toSplit = 'I2eat!Apples22becauseilike?Them'
result = re.split('([0-9,.?:;~!@#$%^&*()])', toSplit)
result

输出:

['I', '2', 'eat', '!', 'Apples', '2', '', '2', 'becauseilike', '?', 'Them']

如果要拆分重复的数字或标点符号,请添加+

result = re.split('([0-9,.?:;~!@#$%^&*()]+)', toSplit)
result

输出:

['I', '2', 'eat', '!', 'Apples', '22', 'becauseilike', '?', 'Them']

【讨论】:

    【解决方案2】:

    您可以将字符串标记为数字、字母和其他不是空格、字母和数字的字符

    re.findall(r'\d+|(?:[^\w\s]|_)+|[^\W\d_]+', toSplit)
    

    这里,

    • \d+ - 1 位以上
    • (?:[^\w\s]|_)+ - 除了单词和空格字符或 _ 之外的 1+ 个字符
    • [^\W\d_]+ - 任意 1+ Unicode 字母。

    请参阅regex demo

    匹配方法比拆分更灵活,因为它还允许对复杂结构进行标记。说,您还想标记十进制(浮点数,双精度...)数字。您只需要使用\d+(?:\.\d+)? 而不是\d+

    re.findall(r'\d+(?:\.\d+)?|(?:[^\w\s]|_)+|[^\W\d_]+', toSplit) 
                 ^^^^^^^^^^^^^
    

    this regex demo

    【讨论】:

      【解决方案3】:

      找到字母范围时使用re.split进行拆分

      >>> import re                                                              
      >>> re.split(r'([A-Za-z]+)', toSplit)                                      
      ['', 'I', '2', 'eat', '!', 'Apples', '22', 'becauseilike', '?', 'Them', '']
      >>>                                                                        
      >>> ' '.join(re.split(r'([A-Za-z]+)', toSplit)).split()                    
      ['I', '2', 'eat', '!', 'Apples', '22', 'becauseilike', '?', 'Them']        
      

      【讨论】:

        猜你喜欢
        • 2013-01-15
        • 1970-01-01
        • 1970-01-01
        • 2012-01-22
        • 1970-01-01
        • 1970-01-01
        • 2013-02-17
        • 1970-01-01
        相关资源
        最近更新 更多