2016-12-29 38 views
0

我有這樣一個字符串,我必須從中提取值。在Python中提取每個值

process({ "www.google.com": { "target": "google.com", "0": [ 94, 71 ], "1": [ 94, 71 ], "2": [ 94, 71 ], "4": [ 93, 67 ], "categories": { "501": 99, "301": 47, "304": 5 } } }) 

我想訪問諸如"0": [94, 71]"categories": { "501": 99, "301": 47, "304": 5 }值等

+0

歡迎計算器!請閱讀 [如何提出問題](https://stackoverflow.com/help/asking)並提供 [最小,完整且可驗證的示例](https://stackoverflow.com/help/mcve) 重現您的問題。 –

+0

發佈你到目前爲止嘗試過的嗎? –

+0

'[ 'www.googl.com'] [ '0']'和'[ 'www.google.com'] [ '類別']'等 – furas

回答

0

你可以嘗試這樣的事情:

import re 
import ast 

a = """process({ "www.google.com": { "target": "google.com", "0": [ 94, 71 ], "1": [ 94, 71 ], "2": [ 94, 71 ], "4": [ 93, 67 ], "categories": { "501": 99, "301": 47, "304": 5 } } }) 
""" 

d = ast.literal_eval(re.findall(r'{.*}', a)[0]) 
print d, '\n' 
print d['www.google.com']['0'], '\n' 
print d['www.google.com']['categories'] 

輸出:

{'www.google.com': {'target': 'google.com', '1': [94, 71], '0': [94, 71], '2': [94, 71], '4': [93, 67], 'categories': {'301': 47, '304': 5, '501': 99}}} 

[94, 71] 

{'301': 47, '304': 5, '501': 99} 
+0

你可以更進一步,用'ast.literal_eval(ast.parse(一)。體[0] .value.args [0])'。 – bereal

+0

@bereal如何看待內部的各個步驟什麼內部發生了什麼? – MYGz

+0

只是對它進行解剖點之間,如'ast.parse(a).body'是'_ast.Expr'等列表。 – bereal