如何在 Python 中分割 CamelCase

我想要达到的是这样的效果:

>>> camel_case_split("CamelCaseXYZ")
['Camel', 'Case', 'XYZ']
>>> camel_case_split("XYZCamelCase")
['XYZ', 'Camel', 'Case']

于是我搜索了一下,发现了这个 完全正则表达式完全正则表达式:

(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])

作为下一个合乎逻辑的步骤,我尝试了:

>>> re.split("(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "CamelCaseXYZ")
['CamelCaseXYZ']

为什么这不工作,以及我如何实现的结果从链接的问题在 python?

编辑: 解决方案摘要

我用一些测试用例测试了所有提供的解决方案:

string:                 ''
AplusKminus:            ['']
casimir_et_hippolyte:   []
two_hundred_success:    []
kalefranz:              string index out of range # with modification: either [] or ['']


string:                 ' '
AplusKminus:            [' ']
casimir_et_hippolyte:   []
two_hundred_success:    [' ']
kalefranz:              [' ']


string:                 'lower'
all algorithms:         ['lower']


string:                 'UPPER'
all algorithms:         ['UPPER']


string:                 'Initial'
all algorithms:         ['Initial']


string:                 'dromedaryCase'
AplusKminus:            ['dromedary', 'Case']
casimir_et_hippolyte:   ['dromedary', 'Case']
two_hundred_success:    ['dromedary', 'Case']
kalefranz:              ['Dromedary', 'Case'] # with modification: ['dromedary', 'Case']


string:                 'CamelCase'
all algorithms:         ['Camel', 'Case']


string:                 'ABCWordDEF'
AplusKminus:            ['ABC', 'Word', 'DEF']
casimir_et_hippolyte:   ['ABC', 'Word', 'DEF']
two_hundred_success:    ['ABC', 'Word', 'DEF']
kalefranz:              ['ABCWord', 'DEF']

总而言之,你可以说@kalefranz 的解与问题不匹配(见最后一个例子) ,而@casimir et hippolyte 的解吃掉了一个空间,因此违反了分裂不应该改变单个部分的观点。其余两个备选方案之间的唯一区别是,我的解决方案在空字符串输入上返回一个包含空字符串的列表,而@200 _ Success 的解决方案返回一个空列表。 我不知道 Python 社区在这个问题上的立场如何,所以我说: 我对任何一个都没有意见。因为200 _ Success 的解决方案更简单,所以我认为它是正确的答案。

38440 次浏览

巨蟒 re.split文件表示:

注意,分割将永远不会在空模式匹配上分割字符串。

看到这个:

>>> re.findall("(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "CamelCaseXYZ")
['', '']

这就很清楚了,为什么分裂不像预期的那样起作用。正如正则表达式所希望的那样,re模块查找空匹配。

由于文档指出这不是 bug,而是预期的行为,因此在尝试创建一个驼峰大小写拆分时必须解决这个问题:

def camel_case_split(identifier):
matches = finditer('(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])', identifier)
split_string = []
# index of beginning of slice
previous = 0
for match in matches:
# get slice
split_string.append(identifier[previous:match.start()])
# advance index
previous = match.start()
# get remaining string
split_string.append(identifier[previous:])
return split_string

下面是另一种需要较少代码且不需要复杂正则表达式的解决方案:

def camel_case_split(string):
bldrs = [[string[0].upper()]]
for c in string[1:]:
if bldrs[-1][-1].islower() and c.isupper():
bldrs.append([c])
else:
bldrs[-1].append(c)
return [''.join(bldr) for bldr in bldrs]

剪辑

上面的代码包含一个优化,它避免了用每个附加字符重新生成整个字符串。如果不考虑这个优化,一个更简单的版本(带注释)可能看起来像

def camel_case_split2(string):
# set the logic for creating a "break"
def is_transition(c1, c2):
return c1.islower() and c2.isupper()


# start the builder list with the first character
# enforce upper case
bldr = [string[0].upper()]
for c in string[1:]:
# get the last character in the last element in the builder
# note that strings can be addressed just like lists
previous_character = bldr[-1][-1]
if is_transition(previous_character, c):
# start a new element in the list
bldr.append(c)
else:
# append the character to the last string
bldr[-1] += c
return bldr

正如@AplusKmins 所解释的,re.split()从来不会在空模式匹配时分裂。因此,您应该尝试找到您感兴趣的组件,而不是进行拆分。

下面是一个使用 re.finditer()模拟拆分的解决方案:

def camel_case_split(identifier):
matches = finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
return [m.group(0) for m in matches]

大多数时候,当你不需要检查字符串的格式时,一个全球性的研究比拆分更简单(为了同样的结果) :

re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))', 'CamelCaseXYZ')

报税表

['Camel', 'Case', 'XYZ']

对付单峰骆驼也可以使用:

re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z]|$)', 'camelCaseXYZ')

注意: (?=[A-Z]|$)可以使用双重否定(带有否定字符类的否定前瞻)来缩短: (?![^A-Z])

使用 re.sub()split()

import re


name = 'CamelCaseTest123'
splitted = re.sub('([A-Z][a-z]+)', r' \1', re.sub('([A-Z]+)', r' \1', name)).split()

结果

'CamelCaseTest123' -> ['Camel', 'Case', 'Test123']
'CamelCaseXYZ' -> ['Camel', 'Case', 'XYZ']
'XYZCamelCase' -> ['XYZ', 'Camel', 'Case']
'XYZ' -> ['XYZ']
'IPAddress' -> ['IP', 'Address']

我只是偶然发现了这种情况,并编写了一个正则表达式来解决它。实际上,它应该适用于任何一组单词。

RE_WORDS = re.compile(r'''
# Find words in a string. Order matters!
[A-Z]+(?=[A-Z][a-z]) |  # All upper case before a capitalized word
[A-Z]?[a-z]+ |  # Capitalized words / all lower case
[A-Z]+ |  # All upper case
\d+  # Numbers
''', re.VERBOSE)

这里的关键是 向前看对第一个可能的情况。它将匹配(并保留)大写字母前的大写字母:

assert RE_WORDS.findall('FOOBar') == ['FOO', 'Bar']

我认为下面是最乐观的

Def count _ word () : Return (re.findall (‘[ A-Z ] ? [ A-Z ] +’,input (‘ please enter your string’))

打印(count _ word ())

我知道这个问题添加了正则表达式的标签。但是,我总是尽可能远离正则表达式。因此,这里是我不使用正则表达式的解决方案:

def split_camel(text, char):
if len(text) <= 1: # To avoid adding a wrong space in the beginning
return text+char
if char.isupper() and text[-1].islower(): # Regular Camel case
return text + " " + char
elif text[-1].isupper() and char.islower() and text[-2] != " ": # Detect Camel case in case of abbreviations
return text[:-1] + " " + text[-1] + char
else: # Do nothing part
return text + char


text = "PathURLFinder"
text = reduce(split_camel, a, "")
print text
# prints "Path URL Finder"
print text.split(" ")
# prints "['Path', 'URL', 'Finder']"

编辑: 正如所建议的,下面是将功能放在单个函数中的代码。

def split_camel(text):
def splitter(text, char):
if len(text) <= 1: # To avoid adding a wrong space in the beginning
return text+char
if char.isupper() and text[-1].islower(): # Regular Camel case
return text + " " + char
elif text[-1].isupper() and char.islower() and text[-2] != " ": # Detect Camel case in case of abbreviations
return text[:-1] + " " + text[-1] + char
else: # Do nothing part
return text + char
converted_text = reduce(splitter, text, "")
return converted_text.split(" ")


split_camel("PathURLFinder")
# prints ['Path', 'URL', 'Finder']

把一个更全面的方法放在其他。它会处理一些问题,比如数字、以小写字母开头的字符串、单字母单词等等。

def camel_case_split(identifier, remove_single_letter_words=False):
"""Parses CamelCase and Snake naming"""
concat_words = re.split('[^a-zA-Z]+', identifier)


def camel_case_split(string):
bldrs = [[string[0].upper()]]
string = string[1:]
for idx, c in enumerate(string):
if bldrs[-1][-1].islower() and c.isupper():
bldrs.append([c])
elif c.isupper() and (idx+1) < len(string) and string[idx+1].islower():
bldrs.append([c])
else:
bldrs[-1].append(c)


words = [''.join(bldr) for bldr in bldrs]
words = [word.lower() for word in words]
return words
words = []
for word in concat_words:
if len(word) > 0:
words.extend(camel_case_split(word))
if remove_single_letter_words:
subset_words = []
for word in words:
if len(word) > 1:
subset_words.append(word)
if len(subset_words) > 0:
words = subset_words
return words

我的要求比 OP 更具体一些。特别是,除了处理所有 OP 案例之外,我还需要其他解决方案所不能提供的以下内容: - 将所有非字母数字输入(例如@# $% ^ & * ()等)视为单词分隔符 - 处理数字如下: 不能在一个词的中间 不能出现在单词的开头,除非这个短语以一个数字开头

def splitWords(s):
new_s = re.sub(r'[^a-zA-Z0-9]', ' ',                  # not alphanumeric
re.sub(r'([0-9]+)([^0-9])', '\\1 \\2',            # digit followed by non-digit
re.sub(r'([a-z])([A-Z])','\\1 \\2',           # lower case followed by upper case
re.sub(r'([A-Z])([A-Z][a-z])', '\\1 \\2', # upper case followed by upper case followed by lower case
s
)
)
)
)
return [x for x in new_s.split(' ') if x]

产出:

for test in ['', ' ', 'lower', 'UPPER', 'Initial', 'dromedaryCase', 'CamelCase', 'ABCWordDEF', 'CamelCaseXYZand123.how23^ar23e you doing AndABC123XYZdf']:
print test + ':' + str(splitWords(test))
:[]
:[]
lower:['lower']
UPPER:['UPPER']
Initial:['Initial']
dromedaryCase:['dromedary', 'Case']
CamelCase:['Camel', 'Case']
ABCWordDEF:['ABC', 'Word', 'DEF']
CamelCaseXYZand123.how23^ar23e you doing AndABC123XYZdf:['Camel', 'Case', 'XY', 'Zand123', 'how23', 'ar23', 'e', 'you', 'doing', 'And', 'ABC123', 'XY', 'Zdf']

工作解决方案,没有 regexp

我不太擅长 Regexp。我喜欢在 IDE 中使用它们进行搜索/替换,但在程序中我尽量避免使用它们。

在纯 python 中有一个非常简单的解决方案:

def camel_case_split(s):
idx = list(map(str.isupper, s))
# mark change of case
l = [0]
for (i, (x, y)) in enumerate(zip(idx, idx[1:])):
if x and not y:  # "Ul"
l.append(i)
elif not x and y:  # "lU"
l.append(i+1)
l.append(len(s))
# for "lUl", index of "U" will pop twice, have to filter that
return [s[x:y] for x, y in zip(l, l[1:]) if x < y]






还有一些测试

def test():
TESTS = [
("aCamelCaseWordT", ['a', 'Camel', 'Case', 'Word', 'T']),
("CamelCaseWordT", ['Camel', 'Case', 'Word', 'T']),
("CamelCaseWordTa", ['Camel', 'Case', 'Word', 'Ta']),
("aCamelCaseWordTa", ['a', 'Camel', 'Case', 'Word', 'Ta']),
("Ta", ['Ta']),
("aT", ['a', 'T']),
("a", ['a']),
("T", ['T']),
("", []),
("XYZCamelCase", ['XYZ', 'Camel', 'Case']),
("CamelCaseXYZ", ['Camel', 'Case', 'XYZ']),
("CamelCaseXYZa", ['Camel', 'Case', 'XY', 'Za']),
]
for (q,a) in TESTS:
assert camel_case_split(q) == a


if __name__ == "__main__":
test()

此解决方案还支持数字、空格和自动删除下划线:

def camel_terms(value):
return re.findall('[A-Z][a-z]+|[0-9A-Z]+(?=[A-Z][a-z])|[0-9A-Z]{2,}|[a-z0-9]{2,}|[a-zA-Z0-9]', value)

一些测试:

tests = [
"XYZCamelCase",
"CamelCaseXYZ",
"Camel_CaseXYZ",
"3DCamelCase",
"Camel5Case",
"Camel5Case5D",
"Camel Case XYZ"
]


for test in tests:
print(test, "=>", camel_terms(test))

结果:

XYZCamelCase => ['XYZ', 'Camel', 'Case']
CamelCaseXYZ => ['Camel', 'Case', 'XYZ']
Camel_CaseXYZ => ['Camel', 'Case', 'XYZ']
3DCamelCase => ['3D', 'Camel', 'Case']
Camel5Case => ['Camel', '5', 'Case']
Camel5Case5D => ['Camel', '5', 'Case', '5D']
Camel Case XYZ => ['Camel', 'Case', 'XYZ']

简单的解决办法:

re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", str(text))
import re


re.split('(?<=[a-z])(?=[A-Z])', 'camelCamelCAMEL')
# ['camel', 'Camel', 'CAMEL'] <-- result


# '(?<=[a-z])'         --> means preceding lowercase char (group A)
# '(?=[A-Z])'          --> means following UPPERCASE char (group B)
# '(group A)(group B)' --> 'aA' or 'aB' or 'bA' and so on

也许这对某些人来说已经足够了:

a = "SomeCamelTextUpper"
def camelText(val):
return ''.join([' ' + i if i.isupper() else i for i in val]).strip()
print(camelText(a))

它不适用于“ CamelXYZ”类型,但适用于“典型的”CamelCase 场景应该就可以了。