尝试从文本文件创建字典列表
所以,我有这个包含以下信息的文本文件:
rect 20 20 80 50 True
tri 80 50 20 35 False
我想要做的是编写一个函数来从文本文件中读取形状的类型和坐标,并以列表的形式返回结果:
readShapes('test.txt')
[{'kind': 'rect', 'bounds': [20, 20, 80, 50], 'fill': True}, {'kind': 'tri', 'bounds': [80, 50, 20, 35], 'fill': False}]
我试过的是这个(虽然它效率低下,但我现在只是想在我的编码过程中慎重考虑):
# reads a file and returns a corresponding list of shapes
def readShapes(filename):
my_file = open(filename, 'r')
lines = my_file.readlines()
fieldnames = ["kindVal", "x0", "y0", "x1", "y1", "fillVal"]
results = []
for line in my_file:
dictionary = {}
fields = line.split(" ")
for i in range(6):
kindVal = str(fieldnames[0])
x0 = int(fieldnames[1])
y0 = int(fieldnames[2])
x1 = int(fieldnames[3])
y1 = int(fieldnames[4])
fillVal = str(fieldnames[5])
shape = {'kind': kindVal, 'bounds': [x0, y0, x1, y1], 'fill': fillVal}
results.append(dictionary)
print(results)
return results
回答
您可以使用扩展的可迭代解包:
res = []
with open('data.txt') as infile:
for line in infile:
kind, *bounds, fill = line.split()
res.append({'kind': kind, 'bounds': bounds, 'fill': fill})
print(res)
输出
[{'kind': 'rect', 'bounds': ['20', '20', '80', '50'], 'fill': 'True'}, {'kind': 'tri', 'bounds': ['80', '50', '20', '35'], 'fill': 'False'}]
如果填充键需要是布尔值,您可以改为:
res.append({'kind': kind, 'bounds': bounds, 'fill': bool(fill == 'True')})
或者,也许更安全:
# from ast import literal_eval
res.append({'kind': kind, 'bounds': bounds, 'fill': literal_eval(fill)})