Python:从.txt、字符串键和数组类型值读取字典

标签 python dictionary text

我已将字典保存到 txt 文件中

f = open("dict_imageData.txt","a")
f.write( str(dict_imageData) + "\n" )
f.close()

保存的txt文件包含

{'002_S_0559': array([ 0.,  0.,  0., ...,  0.,  0.,  0.],dtype=float32)}
{'002_S_1070': array([ 0.,  0.,  0., ...,  0.,  0.,  0.], dtype=float32)}
{'023_S_0604': array([ 0.,  0.,  0., ...,  0.,  0.,  0.], dtype=float32)}

我在加载此字典以及拆分键和值时遇到问题。我尝试了 split 和 eval 但没有成功,因为最后有一个 dtype 语句。

有什么建议吗?

最佳答案

感谢您的评论,是的,我知道使用 JSON 和 pickle,但我对 .txt 文件更感兴趣。我解决了我的问题并找到了如下解决方案:

首先,我将 MyEncoder 类定义为:

class MyEncoder(json.JSONEncoder):
def default(self, obj):
    if isinstance(obj, np.integer):
        return int(obj)
    elif isinstance(obj, np.floating):
        return float(obj)
    elif isinstance(obj, np.ndarray):
        return obj.tolist()
    else:
        return super(MyEncoder, self).default(obj)

由于我的键是字符串,值是数组,因此在写入键值对之前,我将值转储为

dict_imageData [key] = json.dumps(np.float32(np.array(values)), cls = MyEncoder)

现在,我将字典写入文件中

with open('dict_imageData.txt', 'a') as file:
    file.write(json.dumps(dict_imageData))
    file.write("\n")

为了从 .txt 文件读回字典,我使用 eval

with open('dict_imageData.txt','r') as inf:
    lineno = 0
    for line in inf:  
        lineno = lineno + 1 
        print("line number in the file: ", lineno)
        dicts_from_file = dict()
        dicts_from_file = (eval(line))
        for key,value in dicts_from_file.items():
            print("key: ", key, "value: ", value)

关于Python:从.txt、字符串键和数组类型值读取字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649353/

相关文章:

java - 将数据库中的数据放入 map 内的 map 中

c - 如何按行 block 处理 C 中的文本文件?

text - emacs 字符串插入矩形数字向量?

C - 如何读取txt文件中有多少个按空格分割的字符串?

Python 线程名称未显示在 ps 或 htop 上

c# - 尽管字典被实例化,但字典属性始终为 null

python - 试图在数据集中找到最优价格点

python - 如何在运行时从其他文件访问字典

python - Selenium XPath "[@value]"与值不匹配的元素

python - Orator ORM模型创建方法无效SQL