gpt4 book ai didi

python - 我想从 txt 文件中提取 x 和 y 值

转载 作者:行者123 更新时间:2023-11-28 22:11:07 24 4
gpt4 key购买 nike

我有一些代码可以将 x 和 y 值存储到一个 txt 文件中。每次我告诉程序存储数据时,txt 文件都会存储每一行​​的值。

在txt文件中是这样写的:

[(1.0, 1.80), (2.0, 1.80), (3.0, 0.70), 等等...]

我尝试使用 np.genfromtxt() 函数提取值,但我一直在获取值 nan。我通读了文档,但似乎无法解释它。

如何将这些 x 和 y 值存储到变量中,以便我可以在 txt 文件之外进一步使用它们?

最佳答案

使用ast模块

例如:

import ast

with open(filename) as infile: #Read file
for line in infile: #Iterate Each line
print(ast.literal_eval(line)) #Convert to python object

输出:

[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]

关于python - 我想从 txt 文件中提取 x 和 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129844/

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