【问题标题】:Python - Split string into characters while excluding a certain substringPython - 将字符串拆分为字符,同时排除某个子字符串
【发布时间】:2019-12-17 22:41:39
【问题描述】:

我正在尝试将一串字符拆分为一个列表,同时排除某些子字符串。

例如:

>>> sentences = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
>>> substring1 = '<s>'
>>> substring2 = '</s>'
>>> print(split_string(sentences))
['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', 
'.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd',
'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']

如您所见,字符串被拆分为字符,列出的子字符串除外。如何在 Python 中做到这一点?

【问题讨论】:

    标签: python arrays string split substring


    【解决方案1】:

    您可以为此使用re.findall。 :)

    import re
    sentences = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
    print(re.findall(r'<\/?s>|.',sentences))
    

    输出

    ['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', '.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']
    

    【讨论】:

      【解决方案2】:

      你可以使用re.split:

      import re
      s = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
      result = [i for b in re.split('\<s\>|\</s\>', s) for i in ['<s>', *b, '</s>'] if b]
      

      输出:

      ['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', '.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']
      

      【讨论】:

        【解决方案3】:

        您是否试图从上述输出中排除 &lt;s&gt;&lt;/s&gt; 子字符串?

        如果是这样:

        >>> sentences = '<s>I like dogs.</s><s>It\'s Monday today</s>'
        >>> substrings = ['<s>','<\s>']
        >>> [character for character in split(sentences) if character not in substrings]
        

        将给出预期的输出。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-10
          • 2011-11-25
          • 2015-12-28
          • 1970-01-01
          • 2019-05-22
          • 2018-12-11
          • 2015-09-01
          相关资源
          最近更新 更多