【问题标题】:Cannot understand what is going on with rstrip('\n')无法理解 rstrip('\n') 发生了什么
【发布时间】:2018-11-02 21:07:25
【问题描述】:

我正在阅读一本名为Python 中的数据结构和算法 的书。不幸的是,我现在卡住了。

它是关于使用堆栈以相反的顺序重写文件中的行。

您可以忽略ArrayStack 类,因为它只是用来构建堆栈。 请看 reverse_file 函数。

''' Thanks Martineau for editing this to transform bunch of lines to code!'''
class Empty(Exception):
    ''' Error attempting to access an element from an empty container.
    '''
    pass


class ArrayStack:
''' LIFO Stack implementation using a Python list as underlying storage.
'''
    def __init__(self):
        ''' Create an empty stack.
        '''
        self._data = []  # nonpublic list instance

    def __len__(self):
        ''' Return the number of elements in the stack.
        '''
        return len(self._data)

    def is_empty(self):
        ''' Return True if the stack is empty.
        '''
        return len(self._data) == 0

    def push(self, e):
        ''' Add element e to the top of the stack.
        '''
        self._data.append(e)  # new item stored at end of list

    def top(self):
        ''' Return (but do not remove) the element at the top of the stack

        Raise Empty exception if the stack is empty.
        '''
        if self.is_empty():
            raise Empty('Stack is empty.')
        return self._data[-1]  # the last item in the list

    def pop(self):
        ''' Remove and return the element from the top of the stack (i.e, LIFO)

        Raise Empty exception if the stack is empty.
        '''
        if self.is_empty():
            raise Empty('Stack is empty.')
        return self._data.pop()


def reverse_file(filename):
    ''' Overwrite given file with its contents line-by-line reversed. '''
    S = ArrayStack()
    original = open(filename)
    for line in original:
        S.push(line.rstrip('\n'))
    original.close()  # we will re-insert newlines when writing.

    # now we overwrite with contents in LIFO order.
    output = open(filename, 'w')
    while not S.is_empty():
        output.write(S.pop() + '\n')
    output.close()


if __name__ == '__main__':
    reverse_file('6.3.text')

这本书说我们必须使用.rstrip('\n') 方法,因为否则原始文件的最后一行后面跟着(没有换行符)倒数第二行,这是一种特殊情况,即文件的最后一行没有空行final - 如您所知,pep8 总是以“文件末尾没有换行符”来捕捉您。

但是为什么会这样呢?

其他行都很好,为什么只有最后一行有问题?

如果'\n' 会被.rstrip('\n') 删除,那最后有没有换行又有什么关系呢?

【问题讨论】:

    标签: python stack strip


    【解决方案1】:

    换行符分隔行。根据定义,除了最后一行之外的所有行都必须有换行符......因为这就是它们的行。最后一行可能有也可能没有换行符。只要到达文件的末尾,就可以知道它的行尾。

    想一个更简单的算法。您将行读入列表,反转并写入列表中的项目。由于反向,最后一行现在是第一行。如果它没有换行符,当你写第一个和第二个项目时成为第一行。

    通过去除换行符并在末尾手动添加它们来修复它。 rstrip 检查末尾是否有换行符并将其删除。

    【讨论】:

    • 感谢您的回答。我,现在,完全明白了!
    【解决方案2】:

    我认为您可能会使事情过于复杂。实际上,您在阅读时使用line.rstrip('\n') 删除每个'\n'S.pop() + '\n' 只是在写入时为每一行插入这个。否则你会得到一条长线。

    有些文件末尾没有'\n'。整个过程建议在倒写时在最后一行和倒数第二行之间插入一个换行符,否则这两个会合并。

    【讨论】:

    • 感谢您的回答。在我意识到我把这件事复杂化了之后,我的头脑终于开始工作了。
    猜你喜欢
    • 2013-08-26
    • 2021-07-18
    • 1970-01-01
    • 2021-02-18
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多