有谁知道如何根据txt文件将网格返回到shell?

时间:2017-04-02 01:30:41

标签: python text grid

我试图制作一个小型室内设计应用程序,我输入一个txt文件,让我的程序返回shell上的网格。 我只需要知道如何制作一个高度和宽度均为20的网格。

这些是我到目前为止的代码..我只知道如何制作宽度而不是高度。我也不知道如何从我的txt文件中获取数字和字母,但我逐行将我的txt文件放入列表中。

f = open('Apt_3_4554_Hastings_Coq.txt','r')
bigListA = [ line.strip().split(',') for line in f ]

offset = "   "
width = 20
string1 = offset
for number in range(width):
    if len(str(number)) == 1:
        string1 += " " + str(number) + " "
    else:
        string1 += str(number) + " "
print (string1)

2 个答案:

答案 0 :(得分:1)

您可以将房间表示为20x20网格。一个想法是list list;我个人更喜欢dict

通读文件并分配每个点。 (我假设您已经处理过解析文件,因为那不是您发布的问题。)例如:

room[5, 13] = 'C'

然后你可以迭代坐标来提供你的输出。

for i in range(N_ROWS):
    for j in range(N_COLS):
        # Print the character if it exists, or a blank space.
        print(room.get((i, j), default=' '), end='')
    print()  # Start a new line.

答案 1 :(得分:1)

有点矫枉过正,但围绕它做class很有趣:

def decimal_string(number, before=True):
    """
    Convert a number between 0 and 99 to a space padded string.

    Parameters
    ----------
    number: int
        The number to convert to string.
    before: bool
        Whether to place the spaces before or after the nmuber.

    Examples
    --------
    >>> decimal_string(1)
    ' 1'
    >>> decimal_string(1, False)
    '1 '
    >>> decimal_string(10)
    '10'
    >>> decimal_string(10, False)
    '10'
    """
    number = int(number)%100
    if number < 10:
        if before:
            return ' ' + str(number)
        else:
            return str(number) + ' '
    else:
        return str(number)

class Grid(object):
    def __init__(self, doc=None, shape=(10,10)):
        """
        Create new grid object from a given file or with a given shape.

        Parameters
        ----------
        doc: file, None
            The name of the file from where to read the data.
        shape: (int, int), (10, 10)
            The shape to use if no `doc` is provided.
        """
        if doc is not None:
            self.readfile(doc)
        else:
            self.empty_grid(shape)

    def __repr__(self):
        """
        Representation method.
        """
        # first lines
        #    0  1  2  3  4  5  6  7 ...
        #    -  -  -  -  -  -  -  - ...
        number_line = '   '
        traces_line = '   '
        for i in range(len(self.grid)):
            number_line += decimal_string(i) + ' '
            traces_line += ' - '
        lines = ''
        for j in range(len(self.grid[0])):
            line = decimal_string(j, False) + '|'
            for i in range(len(self.grid)):
                line += ' ' + self.grid[i][j] + ' '
            lines += line + '|\n'
        return '\n'.join((number_line, traces_line, lines[:-1], traces_line))

    def readfile(self, doc):
        """
        Read instructions from a file, overwriting current grid.
        """
        with open(doc, 'r') as open_doc:
            lines = open_doc.readlines()
        shape = lines[0].split(' ')[-2:]
        # grabs the first line (line[0]), 
        # splits the line into pieces by the ' ' symbol
        # grabs the last two of them ([-2:])
        shape = (int(shape[0]), int(shape[1]))
        # and turns them into numbers (np.array(..., dtype=int))
        self.empty_grid(shape=shape)
        for instruction in lines[1:]:
            self.add_pieces(*self._parse(instruction))

    def empty_grid(self, shape=None):
        """
        Empty grid, changing the shape to the new one, if provided.
        """
        if shape is None:
            # retain current shape
            shape = (len(self.grid), len(self.grid[0]))
        self.grid = [[' ' for i in range(shape[0])]
                          for j in range(shape[1])]

    def _parse(self, instruction):
        """
        Parse string instructions in the shape:
            "C 5 6 13 13"
        where the first element is the charachter,
        the second and third elements are the vertical indexes
        and the fourth and fifth are the horizontal indexes
        """
        pieces = instruction.split(' ')
        char = pieces[0]
        y_start = int(pieces[1])
        y_stop = int(pieces[2])
        x_start = int(pieces[3])
        x_stop = int(pieces[4])
        return char, y_start, y_stop, x_start, x_stop

    def add_pieces(self, char, y_start, y_stop, x_start, x_stop):
        """
        Add a piece to the current grid.

        Parameters
        ----------
        char: str
            The char to place in the grid.
        y_start: int
            Vertical start index.
        y_stop: int
            Vertical stop index.
        x_start: int
            Horizontal start index.
        x_stop: int
            Horizontal stop index.

        Examples
        --------
        >>> b = Grid(shape=(4, 4))
        >>> b
            0  1  2  3 
            -  -  -  - 
        0 |            |
        1 |            |
        2 |            |
        3 |            |
            -  -  -  - 
        >>> b.add_pieces('a', 0, 1, 0, 0)
        >>> b
            0  1  2  3 
            -  -  -  - 
        0 | a          |
        1 | a          |
        2 |            |
        3 |            |
            -  -  -  - 
        >>> b.add_pieces('b', 3, 3, 2, 3)
        >>> b
            0  1  2  3 
            -  -  -  - 
        0 | a          |
        1 | a          |
        2 |            |
        3 |       b  b |
            -  -  -  - 
        """
        assert y_start <= y_stop < len(self.grid[0]),\
               "Vertical index out of bounds."
        assert x_start <= x_stop < len(self.grid),\
               "Horizontal index out of bounds."
        for i in range(x_start, x_stop+1):
            for j in range(y_start, y_stop+1):
                self.grid[i][j] = char

然后您可以使用file.txt

    20 20
C 5 6 13 13
C 8 9 13 13 
C 5 6 18 18
C 8 9 18 18
C 3 3 15 16
C 11 11 15 16
E 2 3 3 6
S 17 18 2 7
t 14 15 3 6
T 4 10 14 17

并制作:

>>> a = Grid('file.txt')
>>> a
    0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
0 |                                                            |
1 |                                                            |
2 |          E  E  E  E                                        |
3 |          E  E  E  E                          C  C          |
4 |                                           T  T  T  T       |
5 |                                        C  T  T  T  T  C    |
6 |                                        C  T  T  T  T  C    |
7 |                                           T  T  T  T       |
8 |                                        C  T  T  T  T  C    |
9 |                                        C  T  T  T  T  C    |
10|                                           T  T  T  T       |
11|                                              C  C          |
12|                                                            |
13|                                                            |
14|          t  t  t  t                                        |
15|          t  t  t  t                                        |
16|                                                            |
17|       S  S  S  S  S  S                                     |
18|       S  S  S  S  S  S                                     |
19|                                                            |
    -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -