2016-12-25 48 views
1

我讀了Python食譜第三版和跨在2.6中討論的話題來了「搜索和替換不區分大小寫的文本」,其中作者討論嵌套函數,象下面這樣:困惑這個嵌套函數

def matchcase(word): 
    def replace(m): 
    text = m.group() 
    if text.isupper(): 
     return word.upper() 
    elif text.islower(): 
     return word.lower() 
    elif text[0].isupper(): 
     return word.capitalize() 
    else: 
     return word 
    return replace 

如果我有一些文字如下圖所示:

text = 'UPPER PYTHON, lower python, Mixed Python' 

和我之前和之後打印「文本」的價值,替代正確執行:

x = matchcase('snake') 
print("Original Text:",text) 

print("After regsub:", re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)) 

最後的「打印」命令顯示替代正常情況發生,但我不知道該嵌套函數如何「獲得」了:

SNAKE, snake, Snake 

PYTHON, python, Python 

如需要的話與被取代

內部函數如何取代其值'm'?
當調用matchcase('snake')時,單詞取值'snake'。
不清楚'm'的價值是什麼。

在這種情況下,任何人都可以清楚地理解這一點嗎?

感謝。

回答

0

當傳遞函數作爲第二個參數,以re.sub,根據the documentation

它被稱爲爲每個非重疊發生模式的。該函數採用單個匹配對象參數,並返回替換字符串。

matchcase()函數本身返回replace()功能,所以當你這樣做:

re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE) 

什麼情況是,matchcase('snake')回報replace,然後將模式'python'的每個非重疊發生的匹配對象作爲m參數傳遞給replace函數。如果這讓你感到困惑,不要擔心;它通常是令人困惑的。

下面是一個簡單得多的嵌套功能的交互式會話,應該讓事情更清晰:

In [1]: def foo(outer_arg): 
    ...:  def bar(inner_arg): 
    ...:   print(outer_arg + inner_arg) 
    ...:  return bar 
    ...: 

In [2]: f = foo('hello') 

In [3]: f('world') 
helloworld 

所以f = foo('hello')被分配,看起來像下面的一個變量f功能:

def bar(inner_arg): 
    print('hello' + inner_arg) 

f然後可以像這樣調用f('world'),這就像調用bar('world')一樣。我希望這會讓事情更清楚。