使用python3从样式为列表和元组的txt文件中获取信息

2024-09-29 07:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件“test.txt”。其数据采用以下样式:

[(5.0, 1.12, 1, ((False, []), 0.85)), (4.21, 3.2, 2, ((True, []), 0.7997))]\n

本例仅显示文件中的第一行,该文件实际上有20行

在每一行中,它以“[”开始,以“]”结束(请注意“\n”只是一个新行符号)。 如您所见,每行中的模式是“[(()),((()),…]”。在实际情况中,一个“[]”内有10000个“(())”

你知道如何使用python3阅读这些信息吗

我想要的结果是

x_row1 = [[5.0, 1.12, 1],
          [4.21, 3.2, 2],
          ...,
         ]  # len(x_row1) == 10000
y_row1 = [[False, []], 0.85],
          [True, []], 0.7997],
          ...,
         ]  # len(y_row1) == 10000

x_row_all = [[x_row1], [x_row2], ..., [x_row20]]
y_row_all = [[y_row1], [y_row2], ..., [y_row20]]

谢谢


Tags: 文件数据testtxtfalsetruelen样式
1条回答
网友
1楼 · 发布于 2024-09-29 07:30:51

使用^{}

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

>>> import ast
>>> ast.literal_eval('[(5.0, 1.12, 1, ((False, []), 0.85)), (4.21, 3.2, 2, ((True, []), 0.7997))]\n')
[(5.0, 1.12, 1, ((False, []), 0.85)), (4.21, 3.2, 2, ((True, []), 0.7997))]

针对您的具体问题:

import ast

with open('test.txt', 'r') as f:
    all_rows = list(map(ast.literal_eval, f))

x_row_all = [[item[:3] for item in row] for row in all_rows]
y_row_all = [[item[-1] for item in row] for row in all_rows]

如果确实需要元组成为列表,请改为:

def detuple(tup):
    return [detuple(x) if isinstance(x, tuple) else x for x in tup]

x_row_all = [[list(item[:3]) for item in row] for row in all_rows]
# tup = ((False, []), 0.85); detuple(tup) => [[False, []], 0.85]
y_row_all = [[detuple(item[-1]) for item in row] for row in all_rows]

或者,如果将all_rows创建为:

all_rows = [ast.literal_eval(line.replace('(', '[').replace(')', ']') for line in f]

相关问题 更多 >