gpt4 book ai didi

python - 将 txt 文件读取为包含 numpy 数组的 dict

转载 作者:行者123 更新时间:2023-12-01 09:02:49 27 4
gpt4 key购买 nike

我有很多想要读取的 .txt 文件。.txt 文件是通过将 python 字典转换为字符串并将该字符串保存在 .txt 文件中来保存的。

param_string = str(parameters-as-dict)
text_file = open(parameter_file_path, "w")
text_file.write(param_string)
text_file.close()

字典的条目是混合类型(float、int、string...)。在某些文件中,字典的一项是 numpy 数组,并保存在 txt 文件中:

'epsilons': array([...])

因为我想通过名称访问字典中保存的值,所以我现在想读取 txt 文件并将它们再次作为字典加载。这很容易与

f = open(path, 'r')
parameters = ast.literal_eval(f.read())

只要文件中没有 numpy 数组即可。当 numpy-array 存在时,我收到错误:

File ".../python3.6/ast.py", line 84, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.Call object at 0x7fb5428cc630>

这是有道理的,看看 as.literal_eval 文档( https://docs.python.org/2/library/ast.html ),其中说

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

由于我无法以不同的方式重新保存文件,所以我不知道数组位于哪个位置,并且我想避免繁琐的正则表达式解析,因此我正在寻找一种解决方案,将我的 txt 文件转换为包含一个 numpy 数组。

编辑:问题不仅在于 numpy 数组,还在于当我保存一个对象时,例如一个特定的类:

 , 'foo' : <class bar>,

一个解决方案,其中所有无法解析为某种数字/ bool /某些已知数据类型的内容都会自动保存为字符串,就像它可以满足我的需求一样。

最佳答案

我建议采用迭代方法根据需要处理异常。我不喜欢使用eval,也许有更好的方法,但这既快速又肮脏,并且假设您有安全的输入。

parameters = {}    
with open("file.txt") as f:
for line in f:
(key, val) = line.split(':')
if val[:6] == '<class'
# string representation like '<class bar>'
# ast.literal_eval() can't handle this, and neither can eval()
# this is just a string literal, so keep it as such:
parameters[key] = val
continue
try:
parameters[key] = ast.literal_eval(val)
except ValueError as e:
# for unsupported data structures like np.array
parameters[key] = eval(val)

关于python - 将 txt 文件读取为包含 numpy 数组的 dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331966/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com