2011-11-06 4 views
1

임 파일의 큰 배치에서 일부 데이터를 추출하고 내가 수있었습니다파이썬에서 줄 바꿈과 탭이있는 서식 지정 문자열 출력?

장고기구를 사용하여 데이터베이스로 가져 오기 위해 특정 (JSON) 형식으로 변환하려고하는 것은 지금까지 내용 :

\ n "trial_id": NCT00109798, \ n "keyword": 뇌 및 중추 신경계 종양, \ n "pk": 2, \ n "model": trialals.conditions, \ n "fields" \ n "trial_id": NCT00109798, \ n "키워드": 림프종, \ n "{\ n"pk ": 3, \ n"model " \ n "trial_id": NCT00109798, \ n "gender": 둘 다 \ n "minimum_age": 18 년, \ n "pk": 2, \ n "model": 시험판. \ n "text_block": \ n "\ n \ t \ t"pk ": 2, \ n \ t \ t"모델 " \ n \ t \ t "trial_id": NCT00109798, \ n \ t \ t "키워드": 일차 중추 신경계 비호 지킨 림프종 \ n \ t \ t} \ n \ t \ t

... 많은 라인 나중에 .....

연구 치료 완료 후, 환자가 1 년 동안 3 개월마다 준수, 모든 \ 없음 4 개월 1 년 후 3 년 동안 6 개월마다. \ n \ n PROJECTED ACCRUAL : 총 6-25 명의 환자가이 연구에 대해 누적됩니다. \ n, \ n "overall_status": 모집, \ n "단계": \ n "overall_contact": testdata, \ n "위치", \ n "등록" : 4, \ n "lastchanged_date": 2010 년 3 월 31 일, \ n "firstreceived_date": 2005 년 5 월 3 일 \ n "키워드": 2,3, \ n "condition_mesh":, \ n} \ n \ n { \ n "pk": testdata, \ n " \ n "email": \ n "trial_id": NCT00109798, \ n "last_name": Pamela Z. New, MD, \ n "전화 번호" 여기서 n은}} '

출력은 실제로 다음과 같이해야합니다 :

{ 
    "pk": trial_id, 
    "model": trials.trial, 
    "fields": { 
      "trial_id": trial_id, 
      "brief_title": brief_title, 
      "official_title": official_title, 
      "brief_summary": brief_summary, 
      "detailed_Description": detailed_description, 
      "overall_status": overall_status, 
      "phase": phase, 
      "enrollment": enrollment, 
      "study_type": study_type, 
      "condition": _______________, 
      "elligibility": elligibility, 
      "criteria": ______________, 
      "overall_contact": _______________, 
      "location": ___________, 
      "lastchanged_date": lastchanged_date, 
      "firstreceived_date": firstreceived_date, 
      "keyword": __________, 
      "condition_mesh": condition_mesh, 
    } 

    "pk": null, 
    "model": trials.locations, 
    "fields": { 
      "trials_id": trials_id, 
      "facility": facility, 
      "city": city, 
      "state": state, 
      "zip": zip, 
      "country": country, 
    } 

어떤 조언을 많이 감상 할 수있다.

+0

당신은 소스에서 관리 명령 'dumpdata'의 코드를 살펴 https://code.djangoproject.com/browser/django/trunk/을 가질 수있다 django/core/management/commands/dumpdata.py # L111 당신이 수집하려고하는 출력을 들여 쓰기 할 수있는 옵션이 있기 때문에 –

+0

JSON에서는 형식화와 들여 쓰기가 부적합합니다. –

+0

@pastylegs 불행히도 데이터가 DB에서 오지 않아서 dumpdata를 사용할 수 없습니다. XML 파일을 가져 와서 관련 필드를 추출하고 Python을 사용하여 Fixture JSON 형식으로 출력하는 중입니다. 기본적으로 줄 바꿈으로 하나의 거대한 문자열을 반환합니다. – CMaury

답변

3

대안 들여 쓰기 매개 변수를 json.dumps합니다 :

파이썬은 http://docs.python.org/library/pprint.html에서 꽤 프린터가 있습니다. 매우 사용하기 쉽지만 파이썬 객체 만 잘 인쇄합니다 (json 문자열을 제공 할 수없고 형식화 된 출력을 기대할 수 없습니다)

예 :

pydict = {"name":"Chateau des Tours Brouilly","code":"chateau-des-tours-brouilly-2009-1","region":"France > Burgundy > Beaujolais > Brouilly","winery":"Chateau Des Tours","winery_id":"chateau-des-tours","varietal":"Gamay","price":"14.98","vintage":"2009","type":"Red Wine","link":"http://www.snooth.com/wine/chateau-des-tours-brouilly-2009-1/","tags":"colorful, mauve, intense, purple, floral, violet, lively, rich, raspberry, berry","image":"http://ei.isnooth.com/wine/b/7/8/wine_6316762_search.jpeg","snoothrank":3,"available":1,"num_merchants":10,"num_reviews":1} 
from pprint import pprint 
pprint(pydict) 

출력은

{'available': 1, 
'code': 'chateau-des-tours-brouilly-2009-1', 
'image': 'http://ei.isnooth.com/wine/b/7/8/wine_6316762_search.jpeg', 
'link': 'http://www.snooth.com/wine/chateau-des-tours-brouilly-2009-1/', 
'name': 'Chateau des Tours Brouilly', 
'num_merchants': 10, 
'num_reviews': 1, 
'price': '14.98', 
'region': 'France > Burgundy > Beaujolais > Brouilly', 
'snoothrank': 3, 
'tags': 'colorful, mauve, intense, purple, floral, violet, lively, rich, raspberry, berry', 
'type': 'Red Wine', 
'varietal': 'Gamay', 
'vintage': '2009', 
'winery': 'Chateau Des Tours', 
'winery_id': 'chateau-des-tours'} 
+0

감사합니다. – CMaury

1

json 모듈에는 예쁜 프린터가 있습니다. 다음과 같이 시도하십시오 : print json.dumps(s, indent=4).

>>> s = {'pk': 5678, 'model': 'trial model', 'fields': {'brief_title': 'a short title', 'trial_id': 1234}} 

>>> print json.dumps(s, indent=4) 
{ 
    "pk": 5678, 
    "model": "trial model", 
    "fields": { 
     "brief_title": "a short title", 
     "trial_id": 1234 
    } 
}