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() はどちらも機能しません。ブール値ではなくインスタンスを返すためです。コンマがあるかどうかを確認するにはどうすればよいですか?

4

3 に答える 3

5

文字列に文字が含まれているかどうかを Python で確認する最も簡単な方法は、 を使用することinです。例えば:

if ',' in s['name']:
于 2013-07-02T18:35:34.313 に答える
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"
于 2013-07-02T18:36:22.060 に答える