[英]I would like to extract x and y values from a txt file
I have some code which stores x and y values into a txt file. 我有一些将x和y值存储到txt文件中的代码。 The txt file stores the values on each line every time I tell the program to store the data.
每当我告诉程序存储数据时,txt文件都会在每一行上存储值。
It reads like this in the txt file: 它在txt文件中的内容如下:
[(1.0, 1.80), (2.0, 1.80), (3.0, 0.70), etc...]
I tried to extract the values using the np.genfromtxt()
function, but I keep getting the values nan
. 我尝试使用
np.genfromtxt()
函数提取值,但是我一直在获取值nan
。 I read through the documentation but I can't seem to interpret it. 我通读了文档,但似乎无法解释它。
How can I store these x and y values into varibles so that I can further work with them outside of the txt file? 如何将这些x和y值存储到变量中,以便可以在txt文件之外进一步使用它们?
Use ast
module 使用
ast
模块
Ex: 例如:
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
Output: 输出:
[(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)]
If the structure of all those brackets and white spaces is exactly like you posted: 如果所有这些方括号和空格的结构与您发布的内容完全相同:
x = []
y = []
with open('filename.txt') as f:
for line in f:
pairs = line[1:-2].split('),')
for p in pairs:
x.append(float(p.split(', ')[0].strip()[1:]))
y.append(float(p.split(', ')[1].strip()))
# print(x, y)
# [1.0, 2.0, 3.0] [1.8, 1.8, 0.7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.