首页 > 解决方案 > 我想从 txt 文件中提取 x 和 y 值

问题描述

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

它在 txt 文件中是这样写的:

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

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

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

标签: pythonnumpyscipy

解决方案


使用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)]

推荐阅读