【问题标题】:use python3 to get information from a txt file whose style is lists and tuples使用python3从样式为列表和元组的txt文件中获取信息
【发布时间】:2017-01-26 15:42:47
【问题描述】:

我有一个文件“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]]

谢谢。

【问题讨论】:

    标签: python list python-3.x tuples


    【解决方案1】:

    使用ast.literal_eval:

    安全地计算表达式节点或包含 Python 的字符串 文字或容器显示。提供的字符串或节点只能 由以下 Python 文字结构组成:字符串、字节、 数字、元组、列表、字典、集合、布尔值和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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多