2017-10-10 102 views
0
time_sentences = ["Monday: The doctor's appointment is at 2:45pm.", 
        "Tuesday: The dentist's appointment is at 11:30 am.", 
        "Wednesday: At 7:00pm, there is a basketball game!", 
        "Thursday: Be back home by 11:15 pm at the latest.", 
        "Friday: Take the train at 08:10 am, arrive at 09:00am."] 

df['text'].str.replace(r'(\w+day\b)', lambda x: x.group(0)[:3]) 

注意上面,我們沒有一個組,所以我們訪問該組以0組正則表達式超出範圍

我期待,如果我們對組通過1,我們應該得到誤差超出範圍像沒有這樣的小組,但我們沒有得到那個錯誤。

df['text'].str.replace(r'(\w+day\b)', lambda x: x.group(1)[:3]) 

如果我們通過2組,那麼我們超出了範圍錯誤。

df['text'].str.replace(r'(\w+day\b)', lambda x: x.group(2)[:3]) 

任何原因?

+0

組的'(數量)拋出錯誤's等於'(...)'中未轉義括號的對數該模式。 'r'(\ w + day \ b)模式只包含1個捕獲組,因此'group(1)'在匹配時工作良好,'group(2)'即使存在也會拋出異常一場比賽。 –

回答

2

因爲()捕獲組會將捕獲的字符存儲在第一組索引內。 .group().group(0)應返回所有匹配的字符,其中索引1或n返回由相應的捕獲組1或n捕獲的所有字符。

取下正則表達式的那些()捕獲組,它應在訪問x.group(1)

+0

感謝您的澄清 – venkysmarty