[英]Python - Reading a text file into dictionary
我最近開始使用Python編程,而我的一個函數遇到了很大的問題。 我正在嘗試將數據從列表形式的文本文件中提取到Python字典中。 文本文件的格式一致,如下所示:
@text {
n = "test1",
r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
t = ["G:1","H:2"]
}
使用三個鍵:n,r和t; 我將如何使用Python將其值從文本文件讀取到字典中?
到目前為止,盡管嘗試在整個Web上進行研究,但我仍無法成功開發以下代碼,也不知道我哪里出了問題。
f = open('text.txt', 'r')
newDict = {}
for line in f:
n, r, t = line.strip().split('=')
newDict[k.strip()] = v.strip()
我是按照正確的思路還是完全偏離了正常? 從文本文件中將多個鍵和值讀取到字典中的整個概念使我在導入/轉換文件的過程中完全感到困惑。
任何幫助,將不勝感激-預先感謝您。
你可以做:
for line in f:
listedline = line.strip().split('=') # split around the = sign
if len(listedline) > 1: # we have the = sign in there
newDict[listedline[0]] = listedline[1]
但是,您要如何處理此字典中存儲的數據? 它將所有內容存儲為字符串,因此您的列表將是一個很大的字符串。 如果您需要更完善的數據,這並不難,但是您必須告訴我們您要使用此命令要完成的操作。
如果您無法控制輸入文本文件,則可以使用eval
(可能不安全,因此請確保輸入)來解析它們,請參見demo:
source = """@text {
n = "test1",
r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
t = ["G:1","H:2"]
}"""
nrt = ' '.join(source.splitlines()[1:4])
這里nrt
是具有n
, r
和t
定義的空間連接線。 要使其成為有效的python代碼,請用dict(..)
包裝,並評估結果:
obj_code = 'dict({})'.format(nrt)
result = eval(obj_code)
最后:
>>> result
{'r': ['B:1', 'G:2', 'H:3', 'O:4', 'S:5', 'W:6'], 't': ['G:1', 'H:2'], 'n': 'test1'}
不確定是否是這種情況,但是如果您要輸出所述文本文件,並在以后嘗試重新讀取它,則可以使用Pickle而不是簡單地寫入文本文件。 這樣,您就可以輸出對象並在以后又稱為對象序列化中將其讀回。
舉個例子:
import pickle
#to save object
pickle.dump(yourDict, open(yourFile, 'wb'))
#to load it back:
yourDict = pickle.load(open(yourFile, 'rb'))
這是一個粗略的嘗試:
text = """
@text {
n = "test1",
r = ["B:1", "G:2", "H:3", "O:4", "S:5", "W:6"],
t = ["G:1","H:2"]
}"""
import re
from collections import defaultdict
from ast import literal_eval
items = defaultdict(dict)
for name, lines in re.findall(r'(@\w+) {\s*(.*?)\s*}', text, flags=re.S):
for var, val in re.findall(r'\s*(\w+)\s*=\s*(.*?),?$', lines, flags=re.M):
items[name][var] = literal_eval(val)
# defaultdict(<type 'dict'>, {'@text': {'r': ['B:1', 'G:2', 'H:3', 'O:4', 'S:5', 'W:6'], 't': ['G:1', 'H:2'], 'n': 'test1'}})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.