2013-11-24 25 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 

我打算將它轉換成一個字典,鍵爲空頭,多頭,mosts,計數和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,它是一個標準的板載庫。你的文件看起來像這樣。

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

而你的python腳本會是這樣的。

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!是太酷了!