2013-07-02 33 views
2

我試圖執行一堆代碼只有當我正在搜索的字符串包含逗號。僅當字符串包含','時才執行?

下面是一個例子設定的行,我需要解析(名稱是該製表符分隔的文件和列(煩人)包含名稱,程度和實踐的地區列標題:

name        
Sam da Man J.D.,CEP 
Green Eggs Jr. Ed.M.,CEP 
Argle Bargle Sr. MA 
Cersei Lannister M.A. Ph.D. 

我的問題是,一些行中包含一個逗號,後面跟着一個縮寫代表專業的一個「實踐領域」,有些則不是。

我的代碼依賴於每行含有一個逗號,現在我將不得不修改代碼以解釋沒有逗號的行。

def parse_ieca_gc(s): 

    ########################## HANDLE NAME ELEMENT ############################### 

    degrees = ['M.A.T.','Ph.D.','MA','J.D.','Ed.M.', 'M.A.', 'M.B.A.', 'Ed.S.', 'M.Div.', 'M.Ed.', 'RN', 'B.S.Ed.', 'M.D.'] 
    degrees_list = [] 

    # separate area of practice from name and degree and bind this to var 'area' 
    split_area_nmdeg = s['name'].split(',') 
    area = split_area_nmdeg.pop() # when there is no area of practice and hence no comma, this pops out the name + deg and leaves an empty list, that's why 'print split_area_nmdeg' returns nothing and 'area' returns the name and deg when there's no comma 
    print 'split area nmdeg' 
    print area 
    print split_area_nmdeg 

    # Split the name and deg by spaces. If there's a deg, it will match with one of elements and will be stored deg list. The deg is removed name_deg list and all that's left is the name. 
    split_name_deg = re.split('\s',split_area_nmdeg[0]) 
    for word in split_name_deg: 
     for deg in degrees: 
      if deg == word: 
       degrees_list.append(split_name_deg.pop()) 
       name = ' '.join(split_name_deg) 

    # area of practice 
    category = area 

re.search()和re.match()都不起作用,因爲它們返回實例而不是布爾值,所以我應該用什麼來判斷是否有逗號?

+0

'if','in string'。 –

回答

5

python中查看字符串是否包含字符的最簡單方法是使用in。例如:

if ',' in s['name']: 
1
if re.match(...) is not None : 

而不是尋找布爾使用。 Match在成功時返回MatchObject實例,在失敗時返回None。

+0

沒問題!確保檢查python文檔非常好,儘管RE部分有點羅嗦:P – beiller

1

您已在搜索逗號。只需使用該搜索的結果:

split_area_nmdeg = s['name'].split(',') 
if len(split_area_nmdeg) > 2: 
    print "Your old code goes here" 
else: 
    print "Your new code goes here" 
相關問題