`
zhengdl126
  • 浏览: 2508035 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

【汇总】python基础

 
阅读更多

http://www.iteye.com/topic/1092772  Python基础实用技巧

http://pythonmap.iteye.com/category/247013  Python学习笔记-HeadFirstPython

 

http://www.oschina.net/p/pythonwin
http://www.oschina.net/p/idle
http://idle.thomaslauer.com/IdleDownload.html

 

 

http://greybeard.iteye.com/category/188408  python个人系统学习笔记

 

 

 

此笔记为原创,参考教材为中国电力出版社的《Head First Python》
全书用例为Python3.

一、Python安装(Head First Python采用Python3):
    环境win7,Python版本3.2.3
    1、官网www.python.org下载Python3最新版本
    2、安装过程不表
    3、安装完成首在命令行中通过查看版本确定安装成功
        window:D:\python32\python -V  linux:python3 -V

二、IDLE:
    1、IDLE是Python拿一送一的Python IDE(Python的集成开发环境)
    2、IDLE虽说简陋,可对于菜鸟级别的新手足够用了。自带shell,编辑器有代码提示(按下Tab)、代码着色。据说好些大牛平时也用。
    3、IDLE的shell中有代码回退(Alt-p)、代码前进(Alt-n)功能。

 

 

 


第一个习题:列表的数据处理

Python代码  收藏代码
  1. cast = [ 'Cleese' 'Palin' 'Jones' 'Idle' #创建列表并赋值给变量,变量无需声明(list-Python数据类型之一)   
  2. print (cast)  #输出cast变量值(print()-Python BIF)   
  3. print (len(cast))  #输出cast变量值长度(len()-Python BIF)   
  4. print (cast[ 1 ])  #输出被赋值给cast变量的列表中的第2个元素   
  5. cast.append('Gilliam' #向cast中追加一个元素(append方法是列表自带方法)   
  6. cast.pop() #删除列表中最后一个元素,并return最后一个元素   
  7. cast.extend(['Gilliam' 'Chapman' ])  #向列表末尾追加另一个列表,另一个列表中元素作为目标列表中新元素   
  8. cast.remove('Chapman' #删除列表中指定元素   
  9. cast.insert(0 'Chapman' #向列表中指定位置(此处为第一个元素前)插入一个元素   

 

Python代码  收藏代码
  1. '' '''列表的迭代'''   
  2.   
  3. movies = ['movie1' 'movie2' 'movie3' #创建列表并赋值给movies   
  4.   
  5. '' '''for循环是处理列表内个元素的最常用方法  
  6. each_movie为目标标示符;movies为列表;print()代码块为列表元素处理代码'''   
  7. for  each_movie  in  movies:   
  8.     print (each_movie)  
  9.   
  10. '' '''while循环是编写迭代代码的另一种备选方法  
  11. count 为一个计数标示符,用来表示列表状态信息'''   
  12. count = 0   
  13. while  count < len(movies):  
  14.     print (movie[count])  
  15.     count += 1   

 

Python代码  收藏代码
  1. movie = [ 'The Holy Grail' 1975 'director' 91 ,  
  2. ['starring' ,  
  3. ['actor1' 'actor2' 'actor3' ]]]  #列表内元素可以是各种数据类型,可嵌套   
  4.   
  5. '' '''使用if条件语句和for循环语句输出列表中嵌套的列表,本方法之判断嵌套的第一层列表'''   
  6. for  each_item  in  movie:  
  7.     if  isinstance (each_item, list):  #isinstance()为判断条件,返回true or false;isinstance()为BIF,根据参数判断数据类型   
  8.         for  each_item_deep1  in  each_item:   
  9.             print (each_item_deep1)  
  10.     else :  
  11.         print (each_item)  

 

Python代码  收藏代码
  1. '' '''创建一个递归函数解决多层嵌套列表的输出  
  2. pring_lol为函数名  
  3. the_list为参数'''   
  4.   
  5. movie = ['The Holy Grail' 1975 'director' 91 ,  
  6. ['starring' ,  
  7. ['actor1' 'actor2' 'actor3' ]]]  
  8.   
  9. def  print_lol(the_list):  
  10.     for  each_item  in  the_list:  
  11.         if  isinstance(each_item, list):  
  12.             print_lol(each_item)  
  13.         else :  
  14.             print (each_item)  
  15.   
  16. pirint_lol(movie) #函数调用   



零碎:

    1、Python内置函数成为:BIF(built-in functions),print()函数便是其中之一

 

 

 

 

============================== 2 模块和包

 

 

2.1 模块

mymodule.py

#!/usr/bin/python

def sayHi():
    print("hi")

version = "0.1"

 

 

t.py

#!/usr/bin/python


import nester.mymodule

mymodule.sayHi()
print(mymodule.version)

 

 

 

 

2.2 包

新建文件夹nester

 

vim nester.py
#!/usr/bin/python

def say_hi():
    print("hi")

 

新建'setup.py',用于发布

vim setup.py

#!/usr/bin/python
from distutils.core import setup


setup(name = 'nester',
            version = '1.0.0',
            py_modules = ['nester'],
            author = 'pythonmap',
            author_email = 'yuanta11@gmail.com',
            url = 'pythonmap.iteye.com',
            description = 'A simple printer of nested lists')

 

 

构建此distribution:
    终端中输入:python setup.py sdist
安装distribution:
    终端中输入:python setup.py install
查看发布后的nester文件夹结构变化
发布后即可在其他模块中导入使用

 

 

 

# python setup.py sdist
running sdist
running check
reading manifest file 'MANIFEST'
creating nester-1.0.0
making hard links in nester-1.0.0...
hard linking setup.py -> nester-1.0.0
Creating tar archive
removing 'nester-1.0.0' (and everything under it)
# python setup.py install
running install
running build
running build_py
copying nester.py -> build/lib
running install_lib
copying build/lib/nester.py -> /usr/local/python312/lib/python3.1/site-packages
byte-compiling /usr/local/python312/lib/python3.1/site-packages/nester.py to nester.pyc
running install_egg_info
Removing /usr/local/python312/lib/python3.1/site-packages/nester-1.0.0-py3.1.egg-info
Writing /usr/local/python312/lib/python3.1/site-packages/nester-1.0.0-py3.1.egg-info

 

 

在任意目录下

vim t.py

#!/usr/bin/python


import nester

nester.say_hi()

 

 

 

 

======================3.Python第三课-初探文件与异常

从文件读取数据:

常用方式:使用open() BIF和for循环读取基于行的文件内容。

open()使用的基本流程:

Python代码  收藏代码
  1. data = open(filename):  #打开   
  2. print (data.read())  #处理   
  3. data.close() #关闭  

 

 

 

#!/usr/bin/python
import os
if os.path.exists('t.txt'):
    data = open('t.txt')
    print(data.read())
    data.close()
else:
    print('The file is missing')

 

 

 

#!/usr/bin/python

'' '''打开一个名为't.txt'的文件.

把读取到得每行数据利用':'分割处理为讲话者和讲话内容后输出 '''

 

t.txt

1:11
2
3:33

 

import os
if os.path.exists('t.txt'):
    data = open('t.txt')

    for each_line in data:             
        if each_line.find(':') != -1:
            (role, line_spoken) = each_line.split(':', 1)        
            print(role + ' said: ' + line_spoken)            

    data.close()         
else:
    print('The file is missing')

 

 

输出:

1 said: 11

3 said: 33

 

碎碎念:
1、字符串的find ()内置方法,用来检索参数位置,返回指针值,如果未检索到返回-1.
2、字符串的split ()内置方法,用来以sep参数为基准分割字符串,返回分割后的列表。
3、获取方法、函数的使用帮助信息,可以先导入该方法所在模块,然后help之。内置函数直接help之。

Python代码  收藏代码
  1. s =  '2.33'   
  2. help(s.split)  
  3.   
  4. import  os  
  5. help(os.path.exists)  
  6.   
  7. help(open)

 

处理异常:

异常处理:为使代码逻辑更加清晰,先尝试运行代码,然后处理可能会发生的错误。

基本的异常处理:

Python代码  收藏代码
  1. try :  
  2.     #尝试执行的代码   
  3. except :  
  4.     #用于恢复错误的代码   



改进Demo:

Python代码  收藏代码
  1. try :  
  2.     data = open('sketch.txt' )  
  3.   
  4.     for  each_line  in  data:  
  5.         try :  
  6.             (role, line_spoken) = each_line.split(':' 1 )  
  7.             print (role +  ' said: '  + line_spoken)  
  8.         except  ValueError:  #处理try代码块内特定错误类型的异常   
  9.             pass   
  10.   
  11.     data.close() #关闭文件   
  12. except #处理try代码块内所有错误类型的异常   
  13.     print ( 'The file is missing' )  



碎碎念:
看了看下一章,貌似有些对文件和异常处理的补充内容。这节课还是初窥。

 

 

=================4.Python第四课-深入文件与异常(数据持久化)

 

 

 

 

1、创建文件,并将需要持久化得数据写入文件中。

Python代码  收藏代码
  1. '' '''将上课demo中的谈话内容(conversations)按角色(role)的不同,分别存入两个文本文件中'''   
  2.   
  3. man = [] #分别定义两个list 用来存储两个role的conversations   
  4. other = []  
  5.   
  6. try :  
  7.     data = open('sketch.txt' )  
  8.     try :  
  9.         for  each_line  in  data:  
  10.             (role, line_spoken) = each_line.split(':' 1 )  
  11.             line_spoken = line_spoken.strip()  
  12.             if  role ==  'man' #通过判断role来确定要存入的list   
  13.                 man.append(line_spoken)  
  14.             else :  
  15.                 other.append(line_spoken)  
  16.     except  ValueError:  
  17.         pass   
  18.     data.close() #别忘了完成文件操作关闭数据文件对象   
  19. except  IOError:  
  20.     print ( 'The file is missing!' )  
  21.   
  22. try :  
  23.     man_file = open('man_data.txt' 'w' #数据文件对象中的文件参数如果不存在,并且相应目录有相应权限,open()会自动创建文件   
  24.     other_file = open('other_data.txt' 'w' # 'w'为文件数据对象的'写'模式   
  25.   
  26.     print (man, file = man_file)  #print()函数中的file参数为写入的文件名   
  27.     print (other, file = other_file)  
  28.   
  29.     man_file.close() #别忘了完成文件操作关闭数据文件对象   
  30.     other_file.close()  
  31. except  IOError:  
  32.     print ( 'File Error!' )  




2、改进上面代码中的异常处理逻辑和代码:

上面代码中的异常处理方式依旧是不完善的,想想看,如果在man_file.close()语句之前,代码发生了错误,那么数据文件对象是不会被关闭掉的。

改进代码:

Python代码  收藏代码
  1. man = []   
  2. other = []  
  3.   
  4. try :  
  5.     data = open('sketch.txt' )  
  6.     try :  
  7.         for  each_line  in  data:  
  8.             (role, line_spoken) = each_line.split(':' 1 )  
  9.             line_spoken = line_spoken.strip()  
  10.             if  role ==  'man' :  
  11.                 man.append(line_spoken)  
  12.             else :  
  13.                 other.append(line_spoken)  
  14.     except  ValueError:  
  15.         pass   
  16.     data.close()  
  17. except  IOError as ioerr:  #将IOError异常对象赋予ioerr变量   
  18.     print ( 'File Error :'  + str(ioerr))  #将ioerr转换为字符串类型   
  19.   
  20. try :  
  21.     man_file = open('man_data.txt' 'w' )  
  22.     other_file = open('other_data.txt' 'w' )  
  23.   
  24.     print (man, file = man_file)  
  25.     print (other, file = other_file)  
  26. except  IOError as ioerr:  
  27.     print ( 'File Error: '  + str(ioerr))  
  28. finally #无论try代码块或者except代码块中的语句是否被执行,finally代码块中的语句   
  29.     if   'man_file'   in  locals():  #判断数据文件对象是否存在,loclas() BIF返回作用域中所有变量的字典   
  30.         man_file.close()  
  31.     if   'man_file'   in  locals():  
  32.         man_file.close()  




3、Python中 文件处理的语法糖:

利用with语句,可以将文件处理的代码简化,无需考虑关闭文件,裁剪掉文件异常处理语句中的finally语句。
作用一:简化语法,减少工作量。
作用二:通过逻辑抽象,减少码农脑细胞死亡速度和出错概率。

对以上代码第二段之改进:

Python代码  收藏代码
  1. try :  
  2.     with open('man_data.txt' 'w' ) as man_file:  
  3.         print (man, file = man_file)  
  4.     with open('other_data.txt' 'w' ) as other_file:  
  5.         print (other, file = other_file)  
  6. except  IOError as ioerr:  
  7.     print ( 'File Error: '  + str(ioerr))  


OR

Python代码  收藏代码
  1. try :  
  2.     with open('man_data.txt' 'w' ) as man_file, open( 'other_data.txt' 'w' ) as other_file:  
  3.         print (man, file = man_file)  
  4.         print (other, file = other_file)  
  5. except  IOError as ioerr:  
  6.     print ( 'File Error: '  + str(ioerr)) 

 

 

 

 

 

=====================5.将写入文件的列表格式化

 

可当我们试着把保存数据的文件读取出来会怎样呢?

    try: 
        with open('man.txt', 'r') as fman: 
            print(fman.readline()) 
    except IOError as err: 
        print(str(err)) 


执行时,返回一大...串儿字符串。里边包含了man.txt文件中的所有数据。
这种未被格式化的存储方式基本上是没什么用的!除非你把整个文件当一个字符串读出来,然后再去想各种办法解析...


2、把即将写入文本文件的数据格式化:

# vim /tmp/sketch.txt

man:man1
other:other2
man:man2
other:other2
other:other3

 


当然我们可以写出新的代码来实现数据格式化。
可第二课中我们曾经创建过一个nester模块,里边的print_lol函数就是用来格式化列表的。为什么不把它改造一个直接拿来使用呢?不要重复造轮子嘛...OOP吧!

改造print_lol函数

在nester目录中
vim /tmp/nester/nester.py

#!/usr/bin/python

import sys

def print_lol(the_list, level=0, d='\t', indent=False, file_name =sys.stdout):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item, level+1, file_name)
        else:
            if indent:
                for tab_stop in range(level):
                    print(d, end = '', file = file_name)
        print(each_item, file = file_name)

 

 

#cd /tmp/nester

#python setup.py sdist

#python setup.py instal l


改造写入文件的代码块:
# vim /tmp/t.py

#!/usr/bin/python


import nester

man = []
other = []

try:
    data = open('sketch.txt')
    try:
        for each_line in data:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man':
                man.append(line_spoken)
            else:
                other.append(line_spoken)
    except ValueError:
        pass
    data.close()
except IOError as ioerr:
    print('File Error :' + str(ioerr))

try:
    with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
        nester.print_lol(man, file_name = man_file)
        nester.print_lol(other, file_name = other_file)

except IOError as ioerr:
    print('File Error: ' + str(ioerr))


如此便可以利用现有的print_lol函数,实现把格式化后的列表写入文本文件。

 

 

 

 

#cat man_data.txt

man1
man2

#cat other_data.txt
other2
other2
other3

 

 

 

==========================6.持久化相关的另一个模块pickle

 

 

第五课中我们利用nester模块中的print_lol函数对写入文本文件的列表进行了格式化,确保数据的可用性。
可如果我们需要写入其他的数据格式呢?难道要对每一种数据格式都创建一个格式化方法?
要累死程序猿吗?码农也是人啊!

Gudio还有有人情味儿的,python的标准库中有一个pickle模块可以解决这个问题!


使用pickle模块持久化数据

pickle模块可以保存各种数据类型的原始状态,我们不必再为数据写入文件前的格式化而担心了!

 

# vim /tmp/sketch.txt

man:man1
other:other2
man:man2
other:other2
other:other3


将第四课中的代码做如下修改: t.py

Python代码  收藏代码
  1. '' '''使用pickle模块持久化各种数据类型的数据'''   
  2.   
  3. import  pickle  
  4.   
  5. man = []   
  6. other = []  
  7.   
  8. try :  
  9.     data = open('sketch.txt' )  
  10.     try :  
  11.         for  each_line  in  data:  
  12.             (role, line_spoken) = each_line.split(':' 1 )  
  13.             line_spoken = line_spoken.strip()  
  14.             if  role ==  'man' :  
  15.                 man.append(line_spoken)  
  16.             else :  
  17.                 other.append(line_spoken)  
  18.     except  ValueError:  
  19.         pass   
  20.     data.close()  
  21. except  IOError as ioerr:  
  22.     print ( 'File Error :'  + str(ioerr))  
  23.   
  24. try :  
  25.     with open('man_data.txt' 'wb' ) as man_file, open( 'other_data.txt' 'wb' ) as other_file:  #由于pickle以二进制模式存储数据,所以我们需要'wb'参数来以二进制方式操作文件   
  26.         pickle.dump(man, file = man_file) #dump是pickle中的一个方法,用来写入数据   
  27.         pickle.dump(other, file = other_file)  
  28. except  IOError as ioerr:  
  29.     print ( 'File Error: '  + str(ioerr))  
  30. except  pickle.PickleError as perr:  
  31.     print ( 'Pickling Error: '  + str(perr))  #pickle的异常   



这样,我们使用pickle对处理完毕。接下来取出数据看看,是否如我们所愿。 tt.py

Python代码  收藏代码
  1. import  pickle  
  2.   
  3. man_data = []  
  4.   
  5. try :  
  6.     with open('man_file.txt' 'rb' ) as fman:  #用二进制方式打开文件   
  7.         man_data = pickle.load(fman) #pickle中的load方法用于从文件对象中取出数据   
  8. except  IOError as ioerr:  
  9.     print ( 'File Error: '  + str(ioerr))  
  10. except  pickle.PickleError as perr:  
  11.     print ( 'Pickling Error: '  + str(perr))  
  12.   
  13. print (man_data)  


接下来我们可以看到输出到控制台的列表了!

 

 

 

# python t.py
# python tt.py

['man1', 'man2']

 

 

=======================7.提取书中所提供的文本文件中的时间,并且把其中前三个最短时间输出出来。

 

http://pythonmap.iteye.com/blog/1679400

 

 

python中还有一个数据类型——集合。集合跟列表不同点在于集合是无需的,集合内的元素是不能重复的,如果重复,将自动忽略。
所以利用集合的“元素不可重复”的特性来改进一下上边的代码:

 

 

# vim sketch.txt

2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22

 

times中有重复的记录,需要在get_top3中把重复的值处理掉

调用sanitize函数以格式化每个time值

 

 

# vim t.py

#!/usr/bin/python

#格式化a.b

def sanitize(time):
    if ':' in time:
        splitter = ':'
        (mins, secs) = time.split(splitter)
    elif '-' in time:
        splitter = '-'
        (mins, secs) = time.split(splitter)
    else:
        return(time)
    return(mins + '.' + secs)

 

#读取内容
def get_times(file_name):
    times = []
    try:
        with open(file_name) as fdata:
            data = fdata.readline()
            data_list = data.strip().split(',')
            for each_time in data_list:
                clean_time = sanitize (each_time)
                times.append(clean_time)
        return(times)
    except IOError as ioerr:
        print('IO Error: ' + str(ioerr))


#排序从小到大
def get_top3(times_list):
    stimes = set (times_list)
    sorted_times = sorted (stimes)
    return(sorted_times[0:3])


times = get_times('sketch.txt')
print(get_top3(times))

 

输出

['2.01', '2.22', '2.34']

 

 

 

或者

def get_times(file_name): 
    try: 
        with open(file_name) as fdata: 
            data = fdata.readline() 
            data_list = data.strip().split(',') 
            times = [sanitize(each_time) for each_time in data_list] #使用列表推导来取代for迭代中列表的append方法 
        return(times) 
    except IOError as ioerr: 
        print('IO Error: ' + str(ioerr))

 

或者

def get_top3(times_list): 
    sorted_times = sorted(times_list) 
    clean_stimes =[] 
    for each_time in sorted_times: #迭代排序后的每一个列表值 
        if not each_time in clean_stimes: #判断此值是否已存在于clean_stimes列表中 
            clean_stimes.append(each_time) 
    return(clean_stimes[0:3])

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    最全Python基础的知识点复习完整版.doc.pdf

    最全Python基础的知识点复习完整版

    python基础知识汇总

    迅速掌握python基础知识,看这些就够了。

    Python基础语法合集.pdf

    python基础语法合集 python基础语法合集TXT python基础语法合集下载 python基础语法合集下载免费 Python基础语法合集 python语法汇总 python基础语法及知识总结 python基本语法 python基础语法手册pdf python语法...

    python基础梳理.xmind

    python基础梳理.xmind

    Python自学教程-Python基础实战100例.pdf

    Python⾃学教程-Python基础实战100例 第1期-九九乘法表 前⾔:Python是⼀门需要不断实践练习的编程语⾔,本⽂档将AI⼤学堂学员交流群的Python每周练习进⾏汇总,希望各位⼩伙伴能够多进 ⾏实践练习,逐渐爱上这门...

    python基础整理汇总

    python基础整理汇总

    python基础知识点汇总

    python基础知识点汇总,概括性的列出python的基础知识,和一些常用的内建函数等,很基础的东西,总结了学习python第一阶段需要学习的东西。个人总结,仅供参考,后面还有进阶的知识点汇总。

    自学Python基础知识汇总

    自学Python基础知识汇总

    python 基础面试常见汇总

    python 基础面试常见汇总,本人经历整理所得。适合提升基础知识的群体参考。 包含各种概念、算法(含有源代码),还有部分从网络上搜集整理所得。 其它资源参考:https://liuzheng520.blog.csdn.net/ Python由荷兰...

    python基础总结相关汇总

    python基础总结相关汇总

    Python 基础知识 汇总.docx

    Python基础知识

    运维必备Python基础入门到精通.pdf

    运维必备Python基础入门到精通 视频课程汇总 Python 是一种面向对象、解释型计算机程序设计语言,它的语法简洁而清 晰,具有丰富和强大的类库。常被昵称为胶水语言.它能够把用其他语言制作 的各种模块(尤其是 C/C++...

    Python面试题汇总

    某培训机构总结的面试题结合 Python面试题汇总 其中包含python基础、高级企业面试题

    Python编程汇总.pdf

    Python编程汇总 Python基础知识 1. 介绍关于⾃⼰的⼀些详细信息 ⾸先通过⽤户终端输⼊⾃⼰的学号、姓名、性别、出⽣⽇期、⽤户名、所修的课程和所选的教材等基本信息。 然后判断⾃⼰的出⽣年份是否为闰年、创建的⽤...

    Python基础知识汇总

    python基础知识总结,涵盖了整个基础知识框架,对每一个概念及知识点都做出了总结,开启你的python之路吧

    python基础知识梳理.xmind

    python基础知识梳理.xmind

    Python基础理论核心笔记汇总

    第三章 Python 基础 10 第四章 Python 对象 12 第五章 数字 14 第六章 序列: 字符串、列表和元组 16 第七章 映射和集合类型 18 第八章 条件和循环 20 第九章 文件和输入输出 22 第十章 错误和异常 23 第十一...

    Python基础:常用知识点汇总.docx

    Python基础:常用知识点汇总.docx

Global site tag (gtag.js) - Google Analytics