【问题标题】:How to read a file of tuples?如何读取元组文件?
【发布时间】:2021-06-29 03:32:33
【问题描述】:

我有一个这样的 .txt 文件:

(12,13,14,15)
(1,2,4,5)
(1,2,3,4,5)

等等。我想将文件存储到一个形状为 (N,4) 的 numpy 数组中,丢弃那些具有超过 4 个元素的元组。 我试过了 np.genfromtxt('filename.txt', delimiter=',', invalid_raise=False) 但由于“(”和“)”的存在,我在每行的第一个和最后一个词中得到 NaN。我该如何解决?

【问题讨论】:

  • 这不是csv 格式。使用基本 python 获取列表列表,并从中创建数组。

标签: python numpy file io


【解决方案1】:

你首先需要移除弯曲的大括号,这可以通过str的strip方法实现:

"(1,2,3,4)".strip("()")
# "1,2,3,4"

这是一个可行的解决方案:

import numpy as np 

with open("filename.txt") as f:
  data = f.readlines()
  data = [line.strip("()\n").split(",") for line in data]
  array = np.array(data).astype(int)

【讨论】:

    【解决方案2】:

    有一个简单的内置库用于从字符串中获取元组。

    from ast import literal_eval as make_tuple
    tuple_list=[]
    a=open("try.txt","r").readlines()
    for i in a:
        if i!="":
            temp=make_tuple(i)
            if len(temp)<=4:
                tuple_list.append(temp)
                
    print(tuple_list)
    

    try.txt 包含你的元组 最终结果是长度小于等于 4 的所有元组的列表。

    输出:

    [(12, 13, 14, 15), (1, 2, 4, 5)]
    

    参考:Parse a tuple from a string?

    【讨论】:

      【解决方案3】:

      尝试以下解决方案:

      import numpy as np
      #Read and split files with new line character
      with open("temp.txt","r") as f:
          temp = f.read().split("\n")
      # convert tuple stored as string to tuple whoes length = 4
      temp = [eval(elements) for elements in temp if len(eval(elements))==4]
      # convert list to numpy array of size (N,4)
      arr=np.array(temp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多