2013-01-17 37 views
0

我試圖從Python中獲取駝峯字符串的詳細名稱,但不知道如何處理該問題。從駝峯生成詳細名稱

這是用例:

class MyClass(object): 
    def verbose_name(self, camelcase): 
     return "my class" 
     # ^-- here I need a way to calculate the 
     #  value using the camelcase argument 

    def __str__(self): 
     return self.verbose_name(self.__class__.__name__) 

我試圖實現在塊myclass從低級到大寫字母產生的檢測過渡的解決方案,但它是非常程序,不工作,它變得對於這樣一個簡單的任務太複雜了。

任何建議簡單的實施來解決問題?

回答

3

如果我正確理解您的要求,您希望在案例邊界上拆分駱駝案例字符串。正則表達式可以很方便的在這裏

嘗試以下操作執行

>>> ' '.join(re.findall("([A-Z][^A-Z]*)","MyClass")).strip() 
'My Class' 

上述實施如果名稱是不符合駝峯會失敗。在這種情況下,使caps可選

>>> test_case = ["MyClass","My","myclass","my_class","My_Class","myClass"] 
>>> [' '.join(re.findall("([A-Z]?[^A-Z]*)",e)) for e in test_case] 
['My Class ', 'My ', 'myclass ', 'my_class ', 'My_ Class ', 'my Class '] 
+0

argv的! findall!...我試圖在'\ B'上用're.split'分裂一個奇怪的形式,並且有一個超前的斷言,接下來的事情是大寫字母......這樣更好。 – mgilson

0

如何:

def verbose_name(self, camelcase) 
    return re.sub(r'([a-z])([A-Z])',r'\1 \2', camelcase).lower() 
1

大廈作者Abhijit的回答

def verbose_name(self, camelcase): 
    return '_'.join(re.findall("([A-Z][^A-Z]*)", camelcase)).lower()