1. 程式人生 > 實用技巧 >Python 記錄一個坑

Python 記錄一個坑

我有一個專案,批量登入網頁賬號的,在每登入一個賬號的時候,可能會出現驗證備用郵箱的字串,把這個字串提取出來後與原本完整的郵箱進行比對,這裡會出現一個大坑。有時候python之禪的“極簡”還是得放放。

下面是提取的字串,類似:

svi•••••••@vi•.••.com
svi•••••••@fo•••••.com
28••••••@qq.com
svi•••••••@ou•••••.com
vip••••••@ou•••••.com
liu••••••@live.com
svi•••••••@hotmail.com
ann••••••••••@ou•••••.com

把上面的字串儲存後,第二步是要對這些字串進行還原:

 1 if '28' in strResult:
 2     strResult = '[email protected]'
 3 elif 'svi' and '@fo' in strResult:
 4     strResult = '[email protected]'
 5 elif 'svi' and '@vi' in strResult:
 6     strResult = '[email protected]'
 7 elif 'vip' and '@ou' in strResult:
 8     strResult = '[email protected]
' 9 elif 'svi' and '@ou' in strResult: 10 strResult = '[email protected]' 11 elif 'liu' and '@live' in strResult: 12 strResult = '[email protected]' 13 elif 'ann' and '@ou' in strResult: 14 strResult = '[email protected]' 15 elif 'svi' and '@ho' in strResult: 16 strResult = '[email protected]
' 17 18 print(strResult)

上面的程式碼就會出現坑,有些執行的效果都不是預期的,匹配出來的讓人頭暈腦脹,特別是三個outlook.com的郵箱,一會結果是[email protected],一會結果是[email protected],更有甚者想匹配svi和vip的時候會出現結果[email protected]。搞得我頭暈了,卡了一天,然後請教了一個朋友,大神,沒有兩分鐘,就跟我說:“程式碼看上去沒錯,換種寫法試試,elif 'svi' in strResult and '@vi' in strResult”。就是這句話,醍醐灌頂,恍然大悟,所以我就有點怪python之禪了。我以為我寫這個條件的時候寫得已經很死了,他說了之後,我才發現,在完成預期的前提下,他這樣算是寫的最死的了。不說了,將程式碼貼上,記錄一下:

 1 strResult = 'vip••••••@ou•••••.com'
 2 
 3 if '28' in strResult:
 4     strResult = '[email protected]'
 5 elif 'svi' in strResult and '@fo' in strResult:
 6     strResult = '[email protected]'
 7 elif 'svi' in strResult and '@vi' in strResult:
 8     strResult = '[email protected]'
 9 elif 'vip' in strResult and '@ou' in strResult:
10     strResult = '[email protected]'
11 elif 'svi' in strResult and '@ou' in strResult:
12     strResult = '[email protected]'
13 elif 'liu' in strResult and '@live' in strResult:
14     strResult = '[email protected]'
15 elif 'ann' in strResult and '@ou' in strResult:
16     strResult = '[email protected]'
17 elif 'svi' in strResult and '@ho' in strResult:
18     strResult = '[email protected]'
19 
20 print(strResult)

改完後,程式碼執行如預期。