2013-11-24 4 views
-1

에서 원치 않는 인용 부호를 삭제하는 방법 :나는이 파일이 어떻게 사전

shorts: cat, dog, fox 
longs: supercalifragilisticexpialidocious 
mosts:dog, fox 
count: 13 
avglen: 5.6923076923076925 

cat 3 
dog 4 
fox 4 
frogger 1 
supercalifragilisticexpialidocious 1 

내가 같은 키를 사전에이를 변환 할를 반바지, 걷고, 대부분의 사람들의, 수, avglen 및 값 뭐죠로 콜론 다음에. 마지막 부분. 그것은 사전 내의 사전이 될 것입니다.

이 코드가 있습니다

def read_report(filename): 
list1 = [] 
d = {} 
file_name = open(filename) 
for line in file_name: 
    list1.append(line[:-1]) 
d = dict(zip(list1[::2], list1[1::2])) 
file_name.close() 
return d 

을하고 그 결과는 다음과 같습니다 내가 원치 않는 콜론을 제거하려면 어떻게

{'mosts: dog, fox': 'count: 13', 'shorts: cat, dog, fox': 'longs: supercalifragilisticexpialidocious', 'cat 3': 'dog 4', 'fox 4': 'frogger 1', 'avglen: 5.6923076923076925': ''} 

과 같이 보이도록 인용 부호의 위치를 ​​변경 유효한 사전?

+0

가'str.split 시도 (':') '무언가로 시작합니다. – poke

+0

(나는 시도해 보았지만 과거에는 실패했다. 왜 누군가가 OP에'file_name'이 파일명이 아닌지 설명 할 수 있었 을까?) – DSM

+0

마지막 부분이 사전 내의 사전이라면 그 열쇠는 무엇인가? – tMJ

답변

0

이 파일이 txtfile.txt이라는 가정하면 :

lines = open("txtfile.txt").readlines() 
results = {} 
last_part = {} 
for line in lines: 
    if line.strip() == "": 
     continue 
    elif line.startswith(tuple("shorts: longs: mosts: count: avglen:".split())): 
     n, _, v = line.partition(":") 
     results[n.strip()] = v.strip() 
    else: 
     n, v = line.split(" ") 
     last_part[n.strip()] = v.strip() 
results['last_part'] = last_part 
print results 

출력됩니다 :

{'count': '13', 'shorts': 'cat, dog, fox', 'longs': 'supercalifragilisticexpialidocious', 'mosts': 'dog, fox', 'avglen': '5.6923076923076925', 'last_part': {'frogger': '1', 'fox': '4', 'dog': '4', 'supercalifragilisticexpialidocious': '1', 'cat': '3'}}` 
0

JSON을 시험해보십시오. JSON은 표준 라이브러리에 내장되어 있습니다. 파일은 다음과 같습니다.

'{"shorts": ["cat", "dog", "fox"], "longs": "supercalifragilisticexpialidocious", "mosts": ["dog", "fox"], "count": 13, "avglen": "5.6923076923076925", "cat": 3, "dog": 4, "fox": 4, "frogger": 1, "supercalifragilisticexpialidocious": 1}' 

그리고 파이썬 스크립트는 이와 같습니다.

import json 
f = open('my_file.txt','r') 
my_dictionary = json.loads(f.read()) 
f.close() 

print my_dictionary 

출력 :

{u'count': 13, u'shorts': [u'cat', u'dog', u'fox'], u'longs': u'supercalifragilisticexpialidocious', u'mosts': [u'dog', u'fox'], u'supercalifragilisticexpialidocious': 1, u'fox': 4, u'dog': 4, u'cat': 3, u'avglen': u'5.6923076923076925', u'frogger': 1} 

JSON!가 정말 멋지다!