2017-01-24 4 views
-1

텍스트 파일에서 사전을 만들고 싶습니다.Python - 파일의 배열로 사전 만들기

텍스트 파일 :

***Comment line - not to be read by program*** 
jdoe | doe | John Doe | 0001 | True 
jsmith | smith | John Smith | 0002 | False 

사전은 바람직과 같습니다이 필요한 것 무엇 코드

accounts = { 
'jdoe' : ['doe','John Doe', '0001', True], 
'jsmith' : ['smith', 'John Smith', '0002', False] 
} 

이 작동하려면?

+1

이것은 [JSON] (https://docs.python.org/3/library/json.html) – ti7

+0

에 오신 것을 환영합니다로에 StackOverflow에 훨씬 간단 할 것이다 얻는다. 도움말 설명서의 게시 지침을 읽고 따르십시오. [주제] (http://stackoverflow.com/help/on-topic) 및 [묻는 방법] (http://stackoverflow.com/help/how-to-ask) 여기를 참조하십시오. StackOverflow는 코딩 또는 튜토리얼 서비스가 아닙니다. – Prune

+0

@ ti7 왜 json에서 이것이 더 간단할까요? 많은 프로그램이 csv를 읽고 씁니다. 우리는이 데이터의 출처에 대해 알지 못하므로 해당 출처를 수정하는 것이 매우 어려울 수 있습니다. json은 컬트가 아닌 직렬화 프로토콜입니다. – tdelaney

답변

1

는 :

accounts={} 
with open("replacethiswithrealfilename") as f: 
    for line in f: 
     line=line.strip() 
     if line.startswith("***") or not line: 
      continue # ignore comments, ignore empty lines 
     sl=[s.strip() for s in line.split("|")] 
     sl[-1]=(sl[-1]=="True") 
     accounts[sl[0]]=sl[1:] 
0

나는 당신이 무언가를 가지고 있지만 대답을 해줄 것이다. 그렇지만, 파이썬 코딩 책을 읽어야한다. 이 같은

b = {} #your final dictionary 
a = "jdoe | doe | John Doe | 0001 | True" # for loop through the lines in a file, this is just one line 
a = a.split('|') #splits up your string into a list 
b[a[0]] = a[1:] # {'jdoe ': [' doe ', ' John Doe ', ' 0001 ', ' True']} 
1

뭔가 : 간단한 해결책이 될 것

text_file_path = r'your_path' 

accounts = {} 
with open(text_file_path) as f: 
    for line in f.readlines()[1:]: 
     info = line.split(' | ') 
     if info: # possibly ignore blank line at end of file 
      key, values = info[0], info[1:] 
      values[-1] = values[-1] == 'True' 
      accounts[key] = values 

print(accounts) 
0

당신은 튜플의 행으로 파일을 읽고에서 사전을 만들 수 csv 모듈을 사용할 수 있습니다 그 iterable. 복잡한 요소는 주석 행이지만 독자가보기 전에 주석을 제거하는 생성기로 처리 할 수 ​​있습니다. 모두 함께 넣고 당신은

import csv 

def strip_comments(fp): 
    """iterate uncommented lines of a file""" 
    for line in fp: 
     if not line.startswith('***'): 
      yield line 

with open('test.csv', 'r', newline='') as in_file: 
    reader = csv.reader(strip_comments(in_file), delimiter="|", skipinitialspace=True) 
    accounts = {row[0]:row[1:] for row in reader}