可爱的Python_课后习题_CDay−2 完成核心功能

1. 在前文的grep 实现例子中,没有考虑子目录的处理方式,因为如果直接open 目录进行读grep 是古老实用且高效的模式文本匹配工具,在所有的Unix/Linux 系统中都会默认安装,它最常做的事儿是将一堆文本中包含某个模式的文本行找出来,如:~$ cat /proc/cpuinfo | grep

core
core id :0
cpu cores :2
core id :1
cpu cores :2
30 | 实例故事操作,会出现错误,所以请读者修改这个示例代码,以便考虑到子目录这种特殊情况,然后把最后探索出的 cdcGrep()嵌入 pycdc-v0.5.py 中,实现完成版本的PyCDC。

python代码:

def grep(cdcpath, keyword):
    cdcpathlist = list()
    index  = 1

    for root, dirs, files in os.walk(cdcpath):
        for file in files:
            if ".txt" in file:
                cdcpathlist.append(os.path.join(root, file))

    for cdcpath in cdcpathlist:
        cdcfile = open(cdcpath)
        for line in cdcfile.readlines():
            if keyword in line:
                print line

 

2. 编写一个类,实现简单的栈。数据的操作按照先进后出(FILO)的顺序。主要成员 函式为 put(item),实现数据 item 插入栈中;get(),实现从栈中取一个数据。 

python代码:

#encoding=utf-8

class Stack:
    items = list()

    def put(self, item):
        self.items.append(item)


    def get(self):
        length = len(self.items)
        item = self.items[length-1]
        self.items.remove(item)
        return item


if __name__ == "__main__":
    stack = Stack()
    for item in range(1, 10):
        stack.put(item)

    for item in range(1, 10):
        print stack.get()

 

posted @ 2016-12-21 17:32  坏脾气  阅读(149)  评论(0编辑  收藏  举报