【发布时间】: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') 删除,那最后有没有换行又有什么关系呢?
【问题讨论】: