Python核心编程 第九章练习

笔者刚刚开始Python的系统学习,所以在代码上还无法达到pythonic的水准,很多写法也都是按照C++的习惯来写的,希望能有前辈进行交流指导。

欢迎拍砖

9_1

#!/usr/bin/python2
# coding: utf-8

if __name__ == '__main__':
    with open('example.txt') as f:
        for each_line in f:
            if '#' in each_line:
                pos = each_line.find('#')
                if pos > 0:
                    print each_line[: pos]
                else:
                    continue
            else:
                print each_line

9_2

#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            N = int(raw_input('Please input the line number: '))
            for i in range(N):
                print f.readline(),
    else:
        print 'the file name is not valid!'

9_3

#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            lst_line = f.readlines()
            print 'the number of rows are %s' %len(lst_line)
    else:
        print 'the file name is not valid!'

9_4


#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            while True:
                try:
                    raw_input('Press any key to continue...')
                    for i in range(25):
                        line = f.readline()
                        if line == '':
                            raise EOFError
                        print line,
                except(EOFError, KeyboardInterrupt):
                    break

    else:
        print 'the file name is not valid!'

9_5

#!/usr/bin/env python
# encoding: utf-8

from __future__ import division #to make the python do the real division
import os

def Classify(value):
    if value > 90:
        return 'A'
    if value > 80:
        return 'B'
    if value > 70:
        return 'C'
    if value > 60:
        return 'D'
    else:
        return 'F'

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return
if __name__ == '__main__':
    F = raw_input('Please input the file name: ')
    file_path = FilePathCheck(F)
    if file_path:
        with open(file_path) as f:
            str_mark = f.read()
            lst_mark = str_mark.split()
            lst_fmark = [float(i) for i in lst_mark]
            lst_fmark.sort()
            sum_lst = sum(lst_fmark)
            avg_lst = sum_lst/len(lst_fmark)
            print "the average grade is %0.2f" %avg_lst
            class_lst = [Classify(i) for i in lst_fmark]
            print class_lst

9_6

#!/usr/bin/python2
# coding: utf-8

import os

def FilePathCheck(F):
    if os.path.isfile(F):
        return F
    path = os.getcwd()
    curdirF = os.path.join(path, F)
    if os.path.isfile(curdirF):
        return curdirF
    return 
if __name__ == '__main__':
    F1 = raw_input('Please input the file name: ')
    F2 = raw_input('Please input another file name: ')
    file_path1 = FilePathCheck(F1)
    file_path2 = FilePathCheck(F2)
    if file_path1 and file_path2:
        with open(file_path1) as f1:
            with open(file_path2) as f2:
                line1 = f1.readlines()
                line2 = f2.readlines()
                for i in range(min(len(line1), len(line2))):
                    if line1[i] == line2[i]:
                        continue
                    else:
                        print 'The different line is %s' %(i+1)
                        break
                else:
                    print 'All lines are the same'

9_8

参考了birdzb的答案,第一次发现原来模块可以这么用!长见识了。他的链接是:http://blog.csdn.net/birdzb/article/details/49981091。真前辈也!

#/usr/bin/python2
# coding: utf-8

if __name__ == '__main__':
    module = raw_input('Please input a module name: ')
    mod = __import__(module)
    dir_mod = dir(mod)
    print dir_mod
    for i in dir_mod:
        print 'name: %s' %i
        print 'type: %s' %type(getattr(mod, i))
        print 'value: %s' %getattr(mod, i)
        print 

9_9

这是birdzb的答案,他的链接是:http://blog.csdn.net/birdzb/article/details/49981091。

import os
pymodules = {}
path = r'/usr/lib/python2.7'
pyfiles = [f for f in os.listdir(path) if f.endswith('.py')]
for f in pyfiles:
    module = f[:-3]
    pymodules.setdefault(module, '')
    pyfile = path + os.sep + f
    fobj = open(pyfile)
    doc = False
    for line in fobj:
        if line.strip().startswith('"""''"""')and line.strip().endswith('"""'):
            pymodules[module] += line
            fobj.close()
            break
        elif (line.strip().startswith('"""''"""') or line.strip().startswith('r"""')) and len(line)>3:
            doc = True
            pymodules[module] += line
            continue
        elif doc:
            if line == '"""':
                pymodules[module] += line
                fobj.close()
                doc = False
                break
            else:
                pymodules[module] += line
        else:
            continue
    else:
        fobj.close()
hasdoc = []
nodoc = []
for module in pymodules:
    if pymodules[module]:
        hasdoc.append(module)
    else:
        nodoc.append(module)

print 'module has no doc:'
for key in nodoc:
    print key
print '\n'
print 'module has doc:'
for key in hasdoc:
    print 'module:', key
    print 'doc:', pymodules[key]

9_10

这个题目写的规模比较大,主要原因是自己花了3个晚上的时间来学习wxPython的GUI使用(白天要在实验室弄实验室项目(与python无关),忙成狗,实在没办法写python)。总体来讲这个图形界面的模块不难入门,用起来也比Tkinter这个模块更舒服些。之所以放弃已经初步了解的Tkinter,改投wxpython,是因为wxPython使用的人多一些,无论是基础的教程还是排异解难都要方便些,为了提早出坑,所以才开始学习wxPython。想自己了解wxPython的可以访问http://wiki.wxpython.org/Getting%20Started#Getting_started_with_wxPython。
wxPython的安装,linux下可以使用 sudo apt-get install python-wxtools, windows没查过,教程也很多。
现在初步了解了几个控件的使用,但是具体的排版和编辑还是差强人意,请忽略我糟糕的审美,毕竟我的美术是体育老师教的。(这年头教体育背锅上万吨)

#!/usr/bin/env python
# coding: utf-8

import wx
import os
class BankFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(500,100))
        # 创建分页
        self.nb = wx.Notebook(self)

        # 创建储蓄
        self.panel_depos = wx.Panel(self.nb)
        sizer_depos = wx.BoxSizer(wx.VERTICAL)
        self.button_dep_save = wx.Button(self.panel_depos
                                         , label="Save")
        self.button_dep_withdraw = wx.Button(self.panel_depos
                                             , label="Withdraw")
        sizer_depos.Add(self.button_dep_save, 1, wx.EXPAND)
        sizer_depos.Add(self.button_dep_withdraw, 1, wx.EXPAND)
        self.panel_depos.SetSizerAndFit(sizer_depos)
        self.Bind(wx.EVT_BUTTON, self.OnSave, self.button_dep_save)
        self.Bind(wx.EVT_BUTTON, self.OnWithdraw, self.button_dep_withdraw)

        # 创建金融市场
        self.panel_finan = wx.Panel(self.nb)
        sizer_finan = wx.BoxSizer(wx.VERTICAL)
        self.button_fin_borrow = wx.Button(self.panel_finan,
                                           label="Borrow")
        self.button_fin_loan = wx.Button(self.panel_finan,
                                         label="Loan")
        sizer_finan.Add(self.button_fin_borrow, 1, wx.EXPAND)
        sizer_finan.Add(self.button_fin_loan, 1, wx.EXPAND)
        self.panel_finan.SetSizerAndFit(sizer_finan)

        # 将界面放到分页中
        self.nb.AddPage(self.panel_depos, "Deposite")
        self.nb.AddPage(self.panel_finan, "Financial Market")

    def OnSave(self, event):
        self.Hide()     # 隐藏主界面
        self.text = "0" # 初始化数据

        # 读取信息
        file_name = "deposit.txt"
        f = FileExist(file_name, 'r')
        lst_data = f.readlines()
        f.close()
        self.sum_of_depos = float(lst_data[len(lst_data)-1].strip())

        # 设置界面
        self.frame_save = wx.Frame(None, title="Save")
        quote_msg = wx.StaticText(self.frame_save, label="Your bank acount has %s yuan left"
                                  %self.sum_of_depos)
        quote_save = wx.StaticText(self.frame_save, label="How much do you want to save?")
        text_save = wx.TextCtrl(self.frame_save, size = (100, 20))
        button_save = wx.Button(self.frame_save, label="OK")
        save_sizer = wx.BoxSizer(wx.VERTICAL)
        save_sizer.Add(quote_msg, wx.EXPAND)
        save_sizer.Add(quote_save, wx.EXPAND)
        save_sizer.Add(text_save, wx.EXPAND)
        save_sizer.Add(button_save, wx.EXPAND)
        self.frame_save.SetSizerAndFit(save_sizer)
        self.frame_save.Show()

        # 设置响应
        self.frame_save.Bind(wx.EVT_BUTTON, self.Save, button_save)
        self.frame_save.Bind(wx.EVT_TEXT, self.EvtText, text_save)

    def OnWithdraw(self, event):
        self.Hide()
        self.text = "0"

        file_name = "deposit.txt"
        f = FileExist(file_name, 'r')
        lst_data = f.readlines()
        f.close()
        self.sum_of_depos = float(lst_data[len(lst_data)-1].strip())

        self.frame_withdraw = wx.Frame(None, title="Withdraw")
        quote_msg = wx.StaticText(self.frame_withdraw, label="Your bank acount has %s yuan left"
                                  %self.sum_of_depos)
        quote_withdraw = wx.StaticText(self.frame_withdraw, label="How much do you want to withdraw?")
        text_withdraw = wx.TextCtrl(self.frame_withdraw, size = (100, 20))
        button_withdraw = wx.Button(self.frame_withdraw, label="OK")
        withdraw_sizer = wx.BoxSizer(wx.VERTICAL)
        withdraw_sizer.Add(quote_msg, wx.EXPAND)
        withdraw_sizer.Add(quote_withdraw, wx.EXPAND)
        withdraw_sizer.Add(text_withdraw, wx.EXPAND)
        withdraw_sizer.Add(button_withdraw, wx.EXPAND)
        self.frame_withdraw.SetSizerAndFit(withdraw_sizer)
        self.frame_withdraw.Show()

        # 设置响应
        self.frame_withdraw.Bind(wx.EVT_BUTTON, self.Withdraw, button_withdraw)
        self.frame_withdraw.Bind(wx.EVT_TEXT, self.EvtText, text_withdraw)

    def Save(self, event):
        self.frame_save.Close(True)
        self.Show()
        amount = float(self.text.strip())
        self.sum_of_depos += amount
        f = FileExist("deposit.txt", "a")
        f.write("%s\n" %self.sum_of_depos)
        f.close()

    def Withdraw(self, event):
        self.frame_withdraw.Close(True)
        self.Show()
        amount = float(self.text.strip())
        if self.sum_of_depos > amount:
            self.sum_of_depos -= amount
            f = FileExist("deposit.txt", "a")
            f.write("%s\n" %self.sum_of_depos)
            f.close()
        else:
            dlg = wx.MessageDialog(self, "Warning", "You don't have enough deposite", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()


    def EvtText(self, event):
        self.text = event.GetString()

def FileExist(file_name, mode):
    curdir = os.getcwd()
    path = os.path.join(curdir, file_name)
    if (not os.path.isfile(path)):
        f = open(path, "w")
        f.write("0\n")
        f.close()
    f = open(path, mode)
    return f


app = wx.App(False)
frame = BankFrame(None, "Family Account")
frame.Show()
app.MainLoop()

9_11

这个部分也花了很久的时间,主要用于考察正则表达式的含义了。由于刚刚开始完全不懂正则是什么,所以看博客看起来很吃力,唯一让我豁然开朗也最接近于我们的使用的是https://wiki.ubuntu.org.cn/Python%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%93%8D%E4%BD%9C%E6%8C%87%E5%8D%97这个文章,推荐看看。
注:该答案中没有加入判断url是否正确的功能

#!/usr/bin/env python
# coding: utf-8

import wx
import os

class URLFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title)
        file_name = "9_11url.html"
        self.FileCreate(file_name)

        self.nb = wx.Notebook(self)
        # add url panel
        self.add_panel = wx.Panel(self.nb)
        grid = wx.GridBagSizer(hgap=3, vgap=4)
        hSizer = wx.BoxSizer(wx.VERTICAL)
        # add txt blank
        self.lbl_name = wx.StaticText(self.add_panel, label="name")
        self.lbl_url = wx.StaticText(self.add_panel, label="url")
        self.lbl_remark= wx.StaticText(self.add_panel, label="remark")
        self.ctrl_name = wx.TextCtrl(self.add_panel, size = (50, 20))
        self.ctrl_url = wx.TextCtrl(self.add_panel, size=(150, 20))
        self.ctrl_remark = wx.TextCtrl(self.add_panel, size=(100, 20))
        # grid operation
        grid.Add(self.lbl_name, pos=(0,0))
        grid.Add(self.lbl_url, pos=(0,1))
        grid.Add(self.lbl_remark, pos=(0,2))
        grid.Add(self.ctrl_name, pos=(1,0))
        grid.Add(self.ctrl_url, pos=(1,1))
        grid.Add(self.ctrl_remark, pos=(1,2))
        grid.Add((3,2), pos=(2,0))
        # sizer operation
        self.button_add = wx.Button(self.add_panel, label="Add")
        hSizer.Add(grid, 4, wx.ALL, 9)
        hSizer.Add(self.button_add, 1, wx.CENTER)
        self.add_panel.SetSizerAndFit(hSizer)
        self.nb.AddPage(self.add_panel, "Add Url")

        # edit url panel
        self.edit_panel = wx.Panel(self.nb)
        with open(self.path, "r") as f:
            self.lst_urlmsg = f.read().split(r"\n")
            self.len_url = len(self.lst_urlmsg)
        grid_edit = wx.GridBagSizer(hgap=3, vgap=self.len_url)
        hSizer_edit = wx.BoxSizer(wx.VERTICAL)
        self.name_lst = []
        self.url_lst = []
        self.remark_lst = []
        lst_msg=[]
        for i, urlmsg in enumerate(self.lst_urlmsg):
            if urlmsg=="":
                continue
            lst_msg = urlmsg.split(",")
            str_name = lst_msg[0]
            str_url = lst_msg[1]
            str_remark = lst_msg[2]
            ctrl_name = wx.TextCtrl(self.edit_panel, size=(50, 20))
            ctrl_name.AppendText(str_name)
            ctrl_url = wx.TextCtrl(self.edit_panel, size=(150, 20))
            ctrl_url.AppendText(str_url)
            ctrl_remark = wx.TextCtrl(self.edit_panel, size=(100, 20))
            ctrl_remark.AppendText(str_remark)
            grid_edit.Add(ctrl_name, pos=(i,0))
            grid_edit.Add(ctrl_url, pos=(i,1))
            grid_edit.Add(ctrl_remark, pos=(i,2))
            self.name_lst.append(ctrl_name)
            self.url_lst.append(ctrl_url)
            self.remark_lst.append(ctrl_remark)
        self.button_edit = wx.Button(self.edit_panel, label="Edit")
        hSizer_edit.Add(grid_edit, 0, wx.ALL)
        hSizer.Add(self.button_edit, 1, wx.CENTER);
        self.edit_panel.SetSizerAndFit(hSizer_edit)
        self.nb.AddPage(self.edit_panel, "Edit Url")

        self.Bind(wx.EVT_BUTTON, self.Add, self.button_add)
        self.Bind(wx.EVT_BUTTON, self.Edit, self.button_edit)

    def Add(self, event):
        str_name = self.ctrl_name.GetValue().strip()
        str_url = self.ctrl_url.GetValue().strip()
        str_remark = self.ctrl_remark.GetValue().strip()
        with open(self.path, "a") as f:
            if str_name!="" and str_url!="":
                f.write(r"%s,%s,%s\n" %(str_name, str_url, str_remark))

    def Edit(self, event):
        num = len(self.name_lst)
        with open(self.path, "w") as f:
            for i in range(num):
                str_name = self.name_lst[i].GetValue().strip()
                str_url = self.name_lst[i].GetValue().strip()
                str_remark = self.remark_lst[i].GetValue().strip()
                f.write(r"%s,%s,%s\n" %(str_name, str_url, str_remark))

    def FileCreate(self, file_name):
        curdir = os.getcwd()
        self.path = os.path.join(curdir, file_name)
        if (not os.path.isfile(self.path)):
            f = open(self.path, "w")
            f.close()

app = wx.App(False)
frame = URLFrame(None, "URL Management System")
frame.Show()
app.MainLoop()

9_12

这段代码写起来倒是不难,可是为了定位错误原因,花了我整整一个晚上的时间。利用cPickle每次数据都没有保存起来,无论怎么读,都是空,真是折腾死了。
最后成功定位原因:在函数中,我定义了g_users这个全局变量,于是我就在各个class里面自然而然用了c++的逻辑到处使用了。但python其实此时是创建了局部的变量,所以我的传值一直不成功,才导致了这个问题。
最后得到的经验教训是:
全局变量记得加global
全局变量记得加global
全局变量记得加global

#!/usr/bin/python
# coding: utf-8

import wx
import os
import cPickle
import string

availChar = string.lowercase + string.uppercase
g_path = ''
g_users = {}


class AccountFrame(wx.Frame):
    def __init__(self, parent, title):
        global g_path
        global g_users
        wx.Frame.__init__(self, parent, title=title, size=(200, 200))
        file_name = "9_12_Account.txt"
        #self.FileCreate(file_name)
        curdir = os.getcwd()
        self.path = os.path.join(curdir, file_name)
        g_path = self.path
        f = open(self.path, 'r')
        self.users = cPickle.load(f)
        f.close()
        g_users = self.users
        self.btn_log = wx.Button(self, label="user loggin")
        self.btn_show = wx.Button(self, label="Show all users")
        self.btn_del = wx.Button(self, label="Delete user")
        self.btn_quit = wx.Button(self, label="Quit")
        hSizer = wx.BoxSizer(wx.VERTICAL)
        hSizer.Add(self.btn_log, 1, wx.CENTER)
        hSizer.Add(self.btn_show, 1, wx.CENTER)
        hSizer.Add(self.btn_del, 1, wx.CENTER)
        hSizer.Add(self.btn_quit, 1, wx.CENTER)
        self.SetSizerAndFit(hSizer)

        self.Bind(wx.EVT_BUTTON, self.Loggin, self.btn_log)
        #self.Bind(wx.EVT_BUTTON, self.Show, self.btn_show)
        #self.Bind(wx.EVT_BUTTON, self.Delete, self.btn_del)
        self.Bind(wx.EVT_BUTTON, self.Quit, self.btn_quit)
        self.Bind(wx.EVT_CLOSE, self.Quit, self)

    def Loggin(self, event):
        self.Hide()
        LogginFrame(self)
    def Quit(self, event):
        global g_users
        f = open(self.path, 'w')
        cPickle.dump(g_users, f, 0)
        f.close()
        self.Destroy()



    def FileCreate(self, file_name):
        curdir = os.getcwd()
        self.path = os.path.join(curdir, file_name)
        g_path = self.path
        if (not os.path.isfile(self.path)):
            f = open(self.path, "wb")
            f.close()
class LogginFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent=None, title="Loggin")
        global g_users
        self.parent = parent
        self.txt_name = wx.StaticText(self, label="Name:", size=(80,30))
        self.txt_passwd = wx.StaticText(self, label="Password:",size=(80,30))
        self.ctrl_name = wx.TextCtrl(self, size=(150,30))
        self.ctrl_passwd = wx.TextCtrl(self, size=(150,30))
        self.btn_ok = wx.Button(self, label="Ok")
        grid_log = wx.GridBagSizer(hgap=2, vgap=4)
        grid_log.Add(self.txt_name, pos=(0,0))
        grid_log.Add(self.ctrl_name, pos=(0,1))
        grid_log.Add(self.txt_passwd, pos=(1,0))
        grid_log.Add(self.ctrl_passwd, pos=(1,1))
        hSizer = wx.BoxSizer(wx.VERTICAL)
        hSizer.Add(grid_log, 4, wx.ALL, 2)
        hSizer.Add(self.btn_ok, 1, wx.EXPAND)
        self.SetSizerAndFit(hSizer)

        self.Bind(wx.EVT_BUTTON, self.Ok, self.btn_ok)
        self.Bind(wx.EVT_CLOSE, self.Quit, self)
        self.Show()
    def Quit(self, event):
        self.parent.Show()
        self.Destroy()


    def Ok(self, event):
        global g_users
        name = self.ctrl_name.GetValue()
        password = self.ctrl_passwd.GetValue()
        bNameOk = True
        for i in name:
            if i not in availChar:
                bNameOk = False
                break
        if not bNameOk:
            dlg = wx.MessageDialog(self, "Not a available name", "warning", wx.OK)
        elif name in g_users.keys():
            if password == g_users[name]:
                dlg = wx.MessageDialog(self, "welcome back", "info", wx.OK)
            else:
                dlg = wx.MessageDialog(self, "password not correct", "warning", wx.OK)
        else:
            g_users[name] = password

            dlg = wx.MessageDialog(self, name, password, wx.OK)
        dlg.ShowModal()
        dlg.Destroy()
        self.parent.Show()
        self.Destroy()




if __name__ == "__main__":
    app = wx.App(False)
    frame = AccountFrame(None, "Loggin System")
    frame.Show()
    app.MainLoop()

#9_13

#!/usr/bin/python
# coding: utf-8

import sys
if __name__ == "__main__":
    argvs = sys.argv
    print "all the argvs are: ",
    for i in argvs:
        print i,

9_14

#!/usr/bin/python
# coding: utf-8

from __future__ import division
import sys

if __name__ == "__main__":
    argv = sys.argv
    math = []
    for i in range(1, len(argv)):
        math.append(argv[i])
    str_math = ''.join(math)
    b_math = True
    for i in "+-*/^":
        if i in str_math:
            break
    else:
        b_math = False
    if b_math:
        ab = str_math.split(i)
        a = float(ab[0])
        b = float(ab[1])
        if i is "+":
            print a+b
        elif i is "-":
            print a-b
        elif i is "*":
            print a*b
        elif i is "/":
            print a/b
        else:
            print a**b

9_15

#!/usr/bin/python
# coding: utf-8

import sys
import os

if __name__ == "__main__":
    argv = sys.argv
    if len(argv) != 3:
        print "not right parameters"
        os._exit(1)
    file1 = argv[1]
    file2 = argv[2]
    curdir = os.getcwd()
    path1 = os.path.join(curdir, file1)
    path2 = os.path.join(curdir, file2)
    with open(path1, 'r') as f1:
        with open(path2, 'w') as f2:
            data = f1.read()
            f2.write(data)
    print "copy finished"

9_16

发现一个大神,代码写的极其漂亮,推荐大家去看看。下面的答案来自他的主页。http://www.xmanblog.net/2015/04/29/%E3%80%8Apython%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%E3%80%8B%E7%AC%AC%E4%B9%9D%E7%AB%A0%E7%BB%83%E4%B9%A0%E8%A7%A3%E6%9E%90/。

#!/usr/bin/python
# coding: utf-8

def check_text():
    """文档处理函数,对长度超过80的进行截断"""
    f = open("1.txt", "r")
    lines_1 = f.readlines()
    f.close()
    lines_2 = [] #将新生成的文档先储存在lines_2中
    for line in lines_1:
        if len(line)>80:
            if line[80] == " ": #如果81个位置是空格,就不需要考虑单词边界问题
                lines_2.append(line[:80]+"n")
                lines_2.append(line[81:])
            else:
                local = line[:80].rfind(" ") #否则查找最靠近第80个位置的空格截断,保持单词的完整性
                lines_2.append(line[:local]+"n")
                lines_2.append(line[local+1:])
        else:
            lines_2.append(line)
    f = open("1.txt", "w")
    f.writelines(lines_2)
    f.close()

if __name__ == "__main__":
    """主函数"""
    while True: #循环检测每行的长度,直至长度全部小鱼或等于80
        f = open("1.txt", "r")
        lines = f.readlines()
        f.close()
        for line in lines:
            if len(line)>80:
                check_text()
                break
        else:
            break
    print "Done!"

9_17

#!/usr/bin/python
# coding: utf-8

import os
def Create():
    """Create a file"""
    file_name = raw_input("Please input a file name: ")
    current_dir = os.getcwd()
    path = os.path.join(current_dir, file_name)
    f = open(path, "w")
    file_content = []
    print "Please input file content, press Ctrl + d to stop: "
    while True:
        try:
            f.write(raw_input()+"\n")
        except (EOFError, KeyboardInterrupt, IndexError):
            f.close()
            break

def Show():
    """Show the content on the screen"""
    file_name = raw_input("Please input a file name: ")
    current_dir = os.getcwd()
    path = os.path.join(current_dir, file_name)
    f = open(path, "r")
    for line in f:
        print line,
    f.close()

def Edit():
    """Edit a file content"""
    file_name = raw_input("Please input a file name: ")
    current_dir = os.getcwd()
    path = os.path.join(current_dir, file_name)
    with open(path, "r") as f:
        lines = f.readlines()
    row_number = int(raw_input("Please input the row number: "))
    row_content = raw_input("Please edit content: ") + "\n"
    lines[row_number-1] = row_content
    with open(path, "w") as f:
        for line in lines:
            f.write(line)

def Menu():
    CMD = {"c": Create, "s": Show, "e": Edit}
    msg_help = """Please choose:
(C)reate
(S)how
(E)dit
(Q)uit"""
    print msg_help
    msg = "Your choice: "
    while True:
        try:
            choice = raw_input(msg).strip().lower()[0]
        except (EOFError, KeyboardInterrupt, IndexError):
            choice = 'q'
        if choice not in "cseq":
            msg = "Wrong choice, input again: "
            continue
        else:
            break
    if choice is not "q":
        CMD[choice]()

if __name__ == "__main__":
    Menu()

9_18

#!/usr/bin/python
# coding:utf-8

import os

def count(path, ord_of_str):
    sum_of_str = 0
    str_to_find = chr(ord_of_str)
    with open(path) as f:
        for line in f:
            sum_of_str += line.count(str_to_find)
    return sum_of_str

if __name__ == "__main__":
    cur_dir = os.getcwd()
    file_name = raw_input("Please input a file name: ")
    path = os.path.join(cur_dir, file_name)
    ord_of_str = int(raw_input("Please input a number: "))
    sum_of_str = count(path, ord_of_str)
    print "the string used %s times" %sum_of_str

9_19

#!/usr/bin/python
# coding:utf-8

import os

def count(path, ord_of_str):
    sum_of_str = 0
    str_to_find = chr(ord_of_str)
    with open(path) as f:
        for line in f:
            sum_of_str += line.count(str_to_find)
    return sum_of_str

if __name__ == "__main__":
    cur_dir = os.getcwd()
    file_name = raw_input("Please input a file name: ")
    path = os.path.join(cur_dir, file_name)
    ord_of_str = int(raw_input("Please input a number: "))
    sum_of_str = count(path, ord_of_str)
    print "the string used %s times" %sum_of_str

9_20

这个程序很简单,我就不多做介绍了,随便一搜就能找到gzip的资料。

#!/usr/bin/python
# coding:utf-8

import gzip
import os

def gz(file_name):
    """gzip a file at the current work directory"""
    curdir = os.getcwd()
    path = os.path.join(curdir, file_name)
    g_file_name = file_name + ".gz"
    g_file = gzip.GzipFile(g_file_name, "wb")
    print g_file_name
    g_file.write(open(path).read())
    g_file.close()

def ungz(g_file_name):
    """ungzip a file"""
    g_file_name_tuple = os.path.splitext(g_file_name)
    file_name = g_file_name_tuple[0]
    g_file = gzip.GzipFile(g_file_name)
    open(file_name, "w+").write(g_file.read())
    g_file.close()

if __name__ == "__main__":
    CMDS = {"g": gz, "u" : ungz}
    msg_help = """(G)zip
(U)ngzip 
(Q)uit

Please choose: """
    while True:
        try:
            choice = raw_input(msg_help).strip().lower()[0]
        except (EOFError, KeyboardInterrupt, IndexError):
            choice = 'q'
        if choice not in "guq":
            msg_help = "Wrong choice, please input again: "
        else:
            break
    if choice != 'q':
        file_name = raw_input("Input a file name: ")
        CMDS[choice](file_name)

9_21

#!/usr/bin/python
# coding: utf-8

import zipfile
import os

def CreateZipFile(z_file_name):
    """Create a zip file
    z_file_name: zipfile's name"""
    curdir = os.getcwd()
    path = os.path.join(curdir, z_file_name)
    file_name = raw_input("Input a file name: ")
    file_path = os.path.join(curdir,file_name)
    z_file = zipfile.ZipFile(path, "w")
    z_file.write(file_path, file_name, zipfile.ZIP_DEFLATED)
    z_file.close()

def ExtraZipFile(z_file_name):
    """Extract a zip file"""
    curdir = os.getcwd()
    path = os.path.join(curdir, z_file_name)
    z_file = zipfile.ZipFile(path)
    for file in z_file.namelist():
        z_file.extract(file, curdir)
    z_file.close()

if __name__ == "__main__":
    msg_help = """(C)reate a zip file
(E)xtract a zip file
(Q)uit

Please choose: """
    CMDs = {"c" : CreateZipFile, "e" : ExtraZipFile}
    while True:
        try:
            choice = raw_input(msg_help).strip().lower()[0]
        except (EOFError, KeyboardInterrupt, IndexError):
            choice = "q"
        if choice not in "ceq":
            msg_help = "Wrong input, try again: "
            continue
        else:
            break
    if choice is not "q":
        file_name = raw_input("Input a zip file name: ")
        CMDs[choice](file_name)

你可能感兴趣的:(Python,学习笔记)