简体   繁体   English

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

[英]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.

相关问题 我想从 TXT 文件中提取包含 x 和 y 数据的特定行,并按 y 数据对它们进行排序 - I want to extract specific lines which contains x & y data from a TXT file and sort them by y data 我想从 csv 文件中提取字符串的某些部分 - I would like to extract certain part of a string from csv file 从列表中提取x和y值 - Extract x and y values from a list 从折线图中提取 (x,y) 值 - Extract (x,y) values from a line graph 我想将“:”中的单词提取为斜杠 - I would like to extract the words from “:” to slash 如何使用 python 从 txt 文件中提取和组织数据? - How would I extract & organize data from a txt file using python? 从 .txt 文件中提取值到 .xlsx - Extract values from .txt file to .xlsx 如何从 txt 文件中查找和提取值? - How to find and extract values from a txt file? 我想看看新发现的美丽汤链接是否已经在 queue.txt 文件和 crawled.txt 文件中 - I would like to find if the new found links from Beautiful soup is already in the queue.txt file and crawled.txt file 我想创建一个 output txt 文件,格式为 header 是相同的输入 txt 和字典结果中的以下行: - I would like to creating an output txt file with format as header is the same input txt and the below lines from dictionary result:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM