将文本文档坐标 'x, y' 转换为浮点列表对象

Converting text document coordinates 'x, y' to float point list object

我有一个包含坐标的文本文件,我想将其放入基于 python 的图表中(图表来自我正在使用的 kivy.garden.graph 模块)。

当我使用 open().read() 时,文本文件看起来像这样:

(0, 1.836957)
(1, 1.836995)
(2, 1.837073)
(3, 1.837111)
(4, 1.837111)

并且是字符串类型。我需要它进入图形模块:

[(0, 1.836957), (1, 1.836995), (2, 1.837073), (3, 1.837111), (4, 1.837111)]

注意,文本文件会实时更新,图形模块可以处理。或者充其量选择最后创建的 10 个 x,y 点。另外,我可以操作文本文件,因为我自己从外部的另一个函数输出了它。

很抱歉这么简单,但在过去的 24 小时里,我一直在为转换它而绞尽脑汁。我只设法得到这个:

(space末尾逗号后)

[(0, 1.836957), (1, 1.836995), (2, 1.837073), (3, 1.837111), (4, 1.837111), ]

注意多出的逗号和space,而且只是通过replace()进行字符串操作,而不是我需要的是float类型

根据我的经验,如果数据按以下方式保存会更容易: 数字 1 \t 数字 2 \n 无论如何,做你想做的一个选择是:

import json # This library has lost os ways to load and save data
f=open('file.txt','r')
# Remove the \n at the end of each line and replace () for []
# Create the data with all the tuples.
# json only reads list, thats why we have to transforn it into a tuple at the end
data=[tuple(json.loads(l[:-1].replace('(','[').replace(')',']'))) for l in f]
f.close()

这应该有效。如果文件已更新,我认为您应该再次打开它,它将起作用

根据提供的输入和您尝试实现的输出,您可以使用 literal_eval from ast

此外,对于这种特殊情况,如果您使用 readlines() 而不是 read(),可能会更容易管理数据。 readlines 会给你一个列表。

看看这个:

import ast
x = list(ast.literal_eval(','.join(i.strip() for i in open('some_file').readlines())))

输入:

(0, 1.836957)
(1, 1.836995)
(2, 1.837073)
(3, 1.837111)
(4, 1.837111)

输出:(类型将是一个列表)

[(0, 1.836957), (1, 1.836995), (2, 1.837073), (3, 1.837111), (4, 1.837111)]

使用 stripsplit 方法将每一行分成适当的坐标。

with open("myfile.txt") as fh:
    coords = []
    for line in fh:
        line = line.strip('()\n')  # Get rid of the newline and  parentheses
        line = line.split(', ')  # Split into two parts
        c = tuple(float(x) for x in line)  # Make the tuple
        coords.append(c)

整个事情可以通过列表理解更有效地完成;以上内容更具可读性。

with open("myfile.txt") as fh:
    coords = [tuple(float(x) for x in line.strip('()\n').split(', ')) for line in fh]