【问题标题】:How do you put data from a txt file into a Grid?如何将 txt 文件中的数据放入 Grid 中?
【发布时间】:2013-04-24 03:53:42
【问题描述】:

我正在尝试使用一个 .txt 文件,该文件的格式看起来像一个 python 网格中的矩阵。

这是我用来创建网格的类:

class Grid(object):
"""Represents a two-dimensional array."""

    def __init__(self, rows, columns, fillValue = None):
        self._data = Array(rows)
        for row in xrange(rows):
            self._data[row] = Array(columns, fillValue)

    def getHeight(self):
        """Returns the number of rows."""
        return len(self._data)

    def getWidth(self):
        "Returns the number of columns."""
        return len(self._data[0])

    def __getitem__(self, index):
        """Supports two-dimensional indexing with [][]."""
        return self._data[index]

    def __str__(self):
        """Returns a string representation of the grid."""
        result = ""
        for row in xrange(self.getHeight()):
            for col in xrange(self.getWidth()):
                result += str(self._data[row][col]) + " "
            result += "\n"
        return result

它使用另一个名为 Array 的类来构建一维数组并将其变为二维数组。 Code:Grid(10, 10, 1) 将返回一个 10 行 10 列的二维数组,网格中的每个数字都是 1。

这里是数组类

class Array(object):
"""Represents an array."""

def __init__(self, capacity, fillValue = None):
    """Capacity is the static size of the array.
    fillValue is placed at each position."""
    self._items = list()
    for count in xrange(capacity):
        self._items.append(fillValue)

def __len__(self):
    """-> The capacity of the array."""
    return len(self._items)

def __str__(self):
    """-> The string representation of the array."""
    return str(self._items)

def __iter__(self):
    """Supports traversal with a for loop."""
    return iter(self._items)

def __getitem__(self, index):
    """Subscript operator for access at index."""
    return self._items[index]

def __setitem__(self, index, newItem):
    """Subscript operator for replacement at index."""
    self._items[index] = newItem

我希望 1 是我拥有的文本文件中的值,如下所示:

9 9
1 3 2 4 5 2 1 0 1
0 7 3 4 2 1 1 1 1 
-2 2 4 4 3 -2 2 2 1
3 3 3 3 1 1 0 0 0
4 2 -3 4 2 2 1 0 0
5 -2 0 0 1 0 3 0 1
6 -2 2 1 2 1 0 0 1
7 9 2 2 -2 1 0 3 2
8 -3 2 1 1 1 1 1 -2

9,9 代表矩阵的行和列。我唯一可以使用列表的地方是 readline().split() 方法,它将第一行变成一个列表。

我当然有台词;

m = open("matrix.txt", "r")
data = m.read

其中数据以字符串表示形式返回数字,因为它们是从文件夹中格式化的,但我需要一些方法来单独返回每个数字并将其设置为网格中的单元格。有什么想法吗?

编辑:我当前的代码:

g = map(int, m.readline().split())
data = m.read()
matrix = Grid(g[0], g[1], 1)

g[0] 和 g[1] 来自具有行和列变量的列表。这样,任何遵循相同格式的 .txt 文件的第一行都是行和列变量。 我试图弄清楚其余数据如何在不使用列表的情况下替换“1”。

【问题讨论】:

    标签: python file grid


    【解决方案1】:

    这看起来怎么样:

    with open('matrix.txt') as f:
        grid_data = [i.split() for i in f.readlines()]
    

    这将从文件中读取每个数组,并将其格式化为值列表。

    希望这会有所帮助!

    【讨论】:

    • +1 为简单起见...但我认为您不需要条带... split 应该解决这个问题...
    • 没有列表还有其他方法吗?这也是我的想法默认的地方,但是教授不允许在这里使用列表。这让我很困惑。
    • 没有列表是什么意思?您目前正在使用列表.. 但可以肯定...列表只是表示它的最自然方式
    • 编辑了我原来的问题。我可以看到它完成的唯一方法是对数据中的行执行一个 for 循环,但返回的空格和负号与其数字分开......
    • 尼克,该网格只是数据的字符串表示,这是我已经设置的数据。它不允许我从中调用单元格,(即 grid[0][0] 拉起整个东西,而 grid[0][1] 超出了应该是 1 和 3 的范围
    【解决方案2】:
    import numpy
    a_width = 9
    a_height = 9
    data_file = "matrix.dat"
    
    a = numpy.array(open(data_file).read().split(),dtype=int).reshape((a_width,a_height))
    #or another alternative below
    a = numpy.fromfile("matrix.dat",dtype=int,sep=" ").reshape(9,9)
    
    print a
    

    不同的解决方案

    with open(data_file) as f:
        a = map(str.split,f)
    
    print a
    

    这只是尼克伯恩斯代码的更简洁的版本

    【讨论】:

      【解决方案3】:

      一个超级简单的答案(添加了一个新答案,因为它比之前的简单得多)

      # create a grip object
      new_matrix = Grid(9, 9)
      
      with open('matrix.txt') as f:
          # loop through the data
          for i, line in enumerate(f.readlines()):
              line = line.split()
      
              # populate the new_matrix
              for j, value in enumerate(line):
                  new_matrix[i][j] = value
      

      我喜欢这使用 Grid 类来填充矩阵。除了从文件中读取数据外,没有使用列表。

      到达那里(我希望,我想!)

      【讨论】:

      • Append 没有名为 append 的函数。你需要像这样传递它:my_array = Array() 然后,my_array[i].append()
      • 通过我添加到原始问题的类数组,new_matrix[i].append(j) 是导致问题的原因。 new_matrix[i] 是一个 Array 类型,它不能/不会将 j 附加到它
      • 嘿 wes - 现在我们有两个类,它运行得非常好。以上编辑
      • 您可能需要在matrix.txt 中允许第一行(9, 9)
      • 我不认识尼克,我什至取下了我的 readline().split() 用于取下 9、9。仍然出现超出范围的错误。不过,我感谢你今晚给我的所有帮助。
      猜你喜欢
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 2019-11-22
      • 2017-04-23
      • 2022-01-26
      • 2018-12-23
      相关资源
      最近更新 更多