【发布时间】:2015-04-01 11:31:39
【问题描述】:
我一直在玩这个代码,我试图读取没有空格的文本字符串。代码需要通过使用正则表达式识别所有大写字母来分隔字符串。但是我似乎无法让它显示大写字母。
import re
mystring = 'ThisIsStringWithoutSpacesWordsTextManDogCow!'
wordList = re.sub("[^\^a-z]"," ",mystring)
print (wordList)
【问题讨论】:
我一直在玩这个代码,我试图读取没有空格的文本字符串。代码需要通过使用正则表达式识别所有大写字母来分隔字符串。但是我似乎无法让它显示大写字母。
import re
mystring = 'ThisIsStringWithoutSpacesWordsTextManDogCow!'
wordList = re.sub("[^\^a-z]"," ",mystring)
print (wordList)
【问题讨论】:
试试:
re.sub("([A-Z])"," \\1",mystring).split()
这会在每个大写字母前面添加一个空格并在这些空格上拆分。
输出:
['This',
'Is',
'String',
'Without',
'Spaces',
'Words',
'Text',
'Man',
'Dog',
'Cow!']
【讨论】:
作为sub 的替代方案,您可以使用re.findall 查找所有单词(以大写字母开头,后跟零个或多个非大写字符),然后将它们重新组合在一起:
>>> ' '.join(re.findall(r'[A-Z][^A-Z]*', mystring))
'This Is String Without Spaces Words Text Man Dog Cow!'
【讨论】:
试试
>>> 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', '!']
【讨论】:
不是正则表达式解决方案,但您也可以在普通代码中执行:-)
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()
【讨论】: