【问题标题】:Separating a continuous string Python分离一个连续的字符串 Python
【发布时间】:2015-04-01 11:31:39
【问题描述】:

我一直在玩这个代码,我试图读取没有空格的文本字符串。代码需要通过使用正则表达式识别所有大写字母来分隔字符串。但是我似乎无法让它显示大写字母。

import re
mystring = 'ThisIsStringWithoutSpacesWordsTextManDogCow!'
wordList = re.sub("[^\^a-z]"," ",mystring)
print (wordList)

【问题讨论】:

    标签: python regex string list


    【解决方案1】:

    试试:

    re.sub("([A-Z])"," \\1",mystring).split()
    

    这会在每个大写字母前面添加一个空格并在这些空格上拆分。

    输出:

    ['This',
     'Is',
     'String',
     'Without',
     'Spaces',
     'Words',
     'Text',
     'Man',
     'Dog',
     'Cow!']
    

    【讨论】:

      【解决方案2】:

      作为sub 的替代方案,您可以使用re.findall 查找所有单词(以大写字母开头,后跟零个或多个非大写字符),然后将它们重新组合在一起:

      >>> ' '.join(re.findall(r'[A-Z][^A-Z]*', mystring))
      'This Is String Without Spaces Words Text Man Dog Cow!'
      

      【讨论】:

        【解决方案3】:

        试试

        >>> re.split('([A-Z][a-z]*)', mystring)
        ['', 'This', '', 'Is', '', 'String', '', 'Without', '', 'Spaces', '', 'Words', '', 'Text', '', 'Man', '', 'Dog', '', 'Cow', '!']
        

        这为您提供了每个单词的输出。甚至! 也被分离出来。 如果你不想要额外的'',那么如果a是上面命令的输出,你可以通过filter(lambda x: x != '', a)删除它

        >>> filter(lambda x: x != '', a)
        ['This', 'Is', 'String', 'Without', 'Spaces', 'Words', 'Text', 'Man', 'Dog', 'Cow', '!']
        

        【讨论】:

        • filter(None, a) 会更好:-)
        【解决方案4】:

        不是正则表达式解决方案,但您也可以在普通代码中执行:-)

        mystring = 'ThisIsStringWithoutSpacesWordsTextManDogCow!'
        output_list = []
        for i, letter in enumerate(mystring):
            if i!=index and letter.isupper():
                    output_list.append(mystring[index:i])
                    index = i
        else:
            output_list.append(mystring[index:i])
        

        现在就主题而言,这可能是您正在寻找的东西?

        mystring = re.sub(r"([a-z\d])([A-Z])", r'\1 \2', mystring)
        # Makes the string space separated. You can use split to convert it to list
        mystring = mystring.split()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-14
          • 2018-10-28
          相关资源
          最近更新 更多