2013-07-09 4 views
0
나는 다음과 같은 형태의 데이터로 작업하고 있습니다

:왜 내 스크립트가 '이름'열을 수정하지 않습니까?

name phone email website 
Diane Grant Albrecht M.S.   
Lannister G. Cersei M.A.T., CEP 111-222-3333 [email protected] www.got.com 
Argle D. Bargle Ed.M.   
Sam D. Man Ed.M. 000-000-1111 [email protected] www.daManWithThePlan.com 
Sam D. Man Ed.M.    
Sam D. Man Ed.M. 111-222-333  [email protected] www.daManWithThePlan.com 
D G Bamf M.S.   
Amy Tramy Lamy Ph.D.    

그리고는 다음과 같이 얻을 싶습니다 :

당신은 '이름'필드가 포함 할 수있는 것을 알 수 있습니다
name phone email website area degree 
Diane Grant Albrecht     M.S. 
Lannister G. Cersei 111-222-3333 [email protected] www.got.com CEP M.A.T. 
Argle D. Bargle     Ed.M. 
Sam D. Man 000-000-1111, 111-222-3333 [email protected]  [email protected]  Ed.M. 
D G Bamf     M.S. 
Amy Tramy Lamy     Ph.D. 

사람의 이름, 학위 및 실습 영역.

(당신은 또한 알 수 있습니다 그 두 번째 두 개의 '샘 D. 남자 ...'항목.이 질문에 대한, 즉 무관합니다. 다음 단계에서 나는 중복 제거 누락)

그래서 내가 먼저 통해 실행 이 '이름'열을 선택하고 연습 영역 (예 : CEP)과 학위 (예 : Ph.D.)를 구분하기 위해 이름 열을 구문 분석합니다. 나는 이것을 생성 된 필드 '영역'과 '학위'에 쓰고 수정 된/단축 된 이름을 '이름'필드에 저장하려고 시도합니다. 이 절의 끝에서 이상적으로 각 '이름'필드에는 그 사람의 이름 만 포함됩니다.

그러나 스크립트를 실행할 때 사람의 이름 필드에는 아무런 영향을 미치지 않습니다. 이름을 변경하려면 스크립트를 어떻게 조정해야합니까?

감사합니다.

는 여기에 내가 쉽게 소화 할 수 있도록 도움을 주석 한 내 스크립트입니다 '. myjson'

이 시점에서
# Stores a list of dictionaries, each dictionary containing a person's entry with keys corresponding to variable names (ex: [{'name':'Sam', 'phone':'111-111-1111'...},{}]) 
myjson = [] 
# Add fields 'area' and 'degree' to store area of pract and deg earned, which will be parsed from the 'name' field 
with(open("ieca_first_col_fake_text.txt", "rU")) as f: 
    sheet = csv.DictReader(f,delimiter="\t") 
    sheet.fieldnames.append('flag') 
    sheet.fieldnames.append('area') 
    sheet.fieldnames.append('degree') 
    for row in sheet: 
     myjson.append(row) 

, I라는 사전의 목록을 가지고 각 사전은 데이터베이스에 대한 항목을 나타냅니다. 출력

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.', 'M.S.'] 

# Parse name element 
for row in myjson: 

    # check whether the name string has an area of practice by checking if there's a comma separator 
    if ',' in row['name']: 

     # separate area of practice from name and degree and bind this to var 'area'. If error, area is an empty list 
     split_area_nmdeg = row['name'].split(',') 
     try: 
      row['area'].append(split_area_nmdeg.pop()) 
     except AttributeError: 
      row['area'] = [] 

     # 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: 
        try: 
         row['degree'].append(split_name_deg.pop()) 
        except AttributeError: 
         row['degree'] = [] 
       row['name'] = ' '.join(split_name_deg) 
       print row['name'] 

    # if the name string does not contain a comma and therefore does not contain an area of practice 
    else: 
     row['area'] = [] 
     split_name_deg = re.split('\s',row['name']) 
     for word in split_name_deg: 
      for deg in degrees: 
       try: 
        if deg == word: 
         row['degree'].append(split_name_deg.pop()) 
       except AttributeError: 
        row['degree'] = [] 
       row['name'] = ' '.join(split_name_deg) 
       print row['name'] 

확인 :

for row in myjson: 
    print row 

다음과 같습니다

{'website': '', 'name': 'Diane Grant Albrecht M.S.', 'degree': [], 'area': [], 'phone': '', 'flag': None, 'email': ''} 
{'website': 'www.got.com', 'name': 'Lannister G. Cersei M.A.T.', 'degree': [], 'area': [], 'phone': '111-222-3333', 'flag': None, 'email': '[email protected]'} 
{'website': '', 'name': 'Argle D. Bargle Ed.M.', 'degree': [], 'area': [], 'phone': '', 'flag': None, 'email': ''} 
{'website': 'www.daManWithThePlan.com', 'name': 'Sam D. Man Ed.M.', 'degree': [], 'area': [], 'phone': '000-000-1111', 'flag': None, 'email': '[email protected]'} 
{'website': '', 'name': 'Sam D. Man Ed.M.', 'degree': [], 'area': [], 'phone': '', 'flag': None, 'email': ''} 
{'website': 'www.daManWithThePlan.com', 'name': 'Sam D. Man Ed.M.', 'degree': [], 'area': [], 'phone': '111-222-333', 'flag': None, 'email': ' [email protected]'} 
{'website': '', 'name': 'D G Bamf M.S.', 'degree': [], 'area': [], 'phone': '', 'flag': None, 'email': ''} 
{'website': '', 'name': 'Amy Tramy Lamy Ph.D.', 'degree': [], 'area': [], 'phone': '', 'flag': None, 'email': ''} 
first_row {'website': '', 'name': 'Diane Grant Albrecht M.S.', 'degree': [], 'area': [], 'phone': '', 'email': ''} 
+0

로깅 및 pdb 모듈 :'import pdb; pdb.set_trace()'를 호출하면 단계별로 진행할 수 있습니다. 의심스러운 코드 영역에두면 상황을 파악하는 데 도움이됩니다. –

+0

정규식 도구를 배울 때가되었다고 생각하지 않습니까? – eyquem

+0

정규 표현식을 사용하여 구문 분석하는 것은 이름 (제목, 중간 머리 글자/이름 등)에 대한 항목 수에 정렬 할 수있는 방법이 너무 다양 할 때 상당히 복잡합니다. ... – goldisfine

답변

1

내가 여러분 방법을 생각하지 않는다 나는 '이름'필드보고에 진출 학위에 이름이 있는지 여부를 결정하는 것은 작동 중입니다. 불행히도 샘플 데이터를 텍스트 파일에 붙여 넣을 때 탭이 올바르게 유지되었다고 생각하지 않아 사전에 데이터를 읽는 것이 효과가 없기 때문에 전체 테스트를 수행하지 못했습니다. 그러나 위의 인쇄 행에 표시된 출력을 사용하여 사전을 작성하고 아래 코드를 실행하면 해당 숫자를 찾아서 별도의 필드로 나눌 수 있습니다.

+0

게시 중입니다. 결과와 함께 당신에게 돌아갈 것입니다. – goldisfine

+0

아, 그냥 위의 여러 학위를 허용하지 않은 것을 깨달았습니다. 나는 이것을 곧 교정 할 것이다. – ChrisProsser

+0

많은 감사를드립니다. – goldisfine

관련 문제