【问题标题】:Python: Reading dictionary from .txt, string keys and array type valuesPython:从 .txt、字符串键和数组类型值读取字典
【发布时间】:2018-07-16 21:21:48
【问题描述】:

我已将字典保存为 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)}

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

有什么建议吗?

【问题讨论】:

  • 是的,我建议您不要简单地将字典的字符串表示形式转储到文本文件中并自行编写您自己的序列化格式,而是依赖于其中之一现有的许多标准,即 JSON、基于文本的 YAML、用于二进制的 pickle。由于您正在使用numpy,因此可能最好使用numpy 特定格式,使用numpy.savenumpy.savez 用于多个命名数组...
  • 注意:eval 工作,如果适当的名称在范围内,即arraydtypefloat32。但您绝对应该考虑上述选项之一。

标签: python dictionary text


【解决方案1】:

感谢 cmets,是的,我知道使用 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)

【讨论】:

    猜你喜欢
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2020-07-20
    • 2013-07-17
    • 1970-01-01
    • 2020-08-07
    相关资源
    最近更新 更多