2016-01-08 34 views
0

我正在嘗試將URL(而非文本文件)的內容寫入字典。該URL有字典的文字,像這樣一本字典:將字典文本和轉義字符保存爲字典(忽略/刪除轉義字符)

{{"id":15160,"icimsId":247092,"shortDescription":"ABC Leadership Development Program - Retail & Consumer\n\n\u00a3 Competitive basic salary + sign on bonuses + benefits\nClosing date: 30th June 2014\n\nWork hard. Have fun. Make history.\n\nABC opened its","url":"\/jobs\/247092\/ABC-mba-leadership-development-program-uk","title":"ABC MBA Leadership Development Program (UK) ","jobCategory":"Buying, Planning, & Instock Management","location":"GB, Slough","teamCategory":"University Recruiting","team":null}} 

我的猜測是這個URL保存爲TXT文件,然後用這個辦法:

Writing a dict to txt file and reading it back?

不過,我掙扎,因爲一旦我把它變成一個txt文件並試圖評估它,轉義字符會導致一些問題。

同時這工作得很好:

dict_string = r"""{{"id":15160,"icimsId":247092,"shortDescription":"ABC Leadership Development Program - Retail & Consumer\n\n\u00a3 Competitive basic salary + sign on bonuses + benefits\nClosing date: 30th June 2014\n\nWork hard. Have fun. Make history.\n\nABC opened its","url":"\/jobs\/247092\/ABC-mba-leadership-development-program-uk","title":"ABC MBA Leadership Development Program (UK) ","jobCategory":"Buying, Planning, & Instock Management","location":"GB, Slough","teamCategory":"University Recruiting","team":null}}""" 

dict_string = eval(dict_string) 
print dict_string["jobs"] 

回答

3

作爲可能的解決方案之一,我建議使用json模塊,解析這個字符串。

事情是這樣的:

import json 

with open('file_with_dict.txt', 'r') as f: 
    dict_string = json.load(f) 

print(dict_string['jobs']) 

希望,這幫助你。

+0

謝謝drjackild。我只是試過,並得到一個錯誤「TypeError:意外的字符串或緩衝區」 – pugmastaflex

+0

@pugmastaflex對不起,我的壞。我已經編輯答案。使用json.load()而不是json.loads() – drjackild

+0

謝謝!非常有幫助! – pugmastaflex