繁体   English   中英

从文件中读取字典

[英]Read dictionary from file

背景(可选)

我正在编写一个python脚本来分析Abaqus(有限元软件)的输出。 该软件生成具有专有格式的“ .odb”。 但是,由于Dassault(Abaqus软件的所有者)专门开发了python库,因此您可以访问存储在数据库内部的数据。 python脚本必须由软件运行才能访问以下库:

abaqus python myScript.py

但是,以这种方式使用新库确实很困难,而且我无法使其运行matplotlib库。 因此,我想导出在文件中创建的数组,并稍后使用不需要使用abaqus运行的其他脚本来访问它。

问题

为了操纵数据,我使用了集合。 举个例子:

coord2s11=defaultdict(list)

此数组在每个时间步存储一组节点的Z坐标及其应力值:

coord2s11[time_step][node_number][0]=z_coordinate
coord2s11[time_step][node_number][1]=stress_value

对于给定的时间步长,输出为:

defaultdict(<type 'list'>, {52101: [-61.83229635920749, 0.31428813934326172], 52102: [-51.948098314163417, 0.31094224750995636],[...], 52152: [440.18335942363655, -0.11255115270614624]})

以及(所有步骤时间)的全局变量:

defaultdict(<type 'list'>, {0.0: defaultdict(<type 'list'>, {52101: [0.0, 0.0],[...]}), 12.660835266113281: defaultdict(<type 'list'>, {52101: [0.0, 0.0],[...],52152: [497.74876378582229, -0.24295337498188019]})})

如果视觉上不愉快,则非常易于使用! 我使用以下命令将此数组打印在此文件中:

with open('node2coord.dat','w') as f :
    f.write(str(glob))

我试图遵循在这篇文章中找到的解决方案,但是当我尝试读取文件时,将值存储在新的字典中

import ast

with open('node2coord.dat', 'r') as f:
    s = f.read()
    node2coord = ast.literal_eval(s)

我最终遇到了SyntaxError: invalid syntax ,我猜想是来自defaultdict(<type 'list'>在数组中到处都有。

有没有办法获取存储在文件中的数据,还是应该修改写入文件中的数据的方式? 理想情况下,我想创建与我存储的完全相同的数组。

乔尔·约翰逊(Joel Johnson)的解决方案

使用货架创建数据库。 这是一种简便快捷的方法。 以下代码帮助我创建了db:

import os
import shelve

curdir = os.path.dirname(__file__) #defining current directory

d = shelve.open(os.path.join(curdir, 'nameOfTheDataBase')) #creation of the db
d['keyLabel'] = glob # storing the dictionary in "d" under the key 'keyLabel'
d.close() # close the db

“ with”语句对我不起作用。 然后再次打开它:

import os
import shelve


curdir = os.path.dirname(__file__)
d = shelve.open(os.path.join(curdir, 'nameOfTheDataBase')) #opening the db
newDictionary = d['keyLabel'] #loading the dictionary inside of newDictionary
d.close()

如果您遇到错误提示

ImportError: No module named gdbm

只需安装gdbm模块。 对于Linux:

sudo apt-get install python-gdbm

更多信息在这里

如果您可以使用书架 (我认为您会这样做 ,因为它是标准库的一部分),我强烈建议您使用它。 使用搁架是一种存储和加载python对象的简便方法,而无需手动解析和重建它们。

import shelve

with shelve.open('myData') as s:
    s["glob"] = glob

多数民众赞成在存储数据。 然后,当您需要检索它时...

import shelve

with shelve.open('myData') as s:
   glob = s["glob"]

就这么简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM