hudeya 发表于 2017-4-22 12:19:37

【汇总】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代码  





[*]
cast = [
'Cleese'

'Palin'

'Jones'

'Idle'

#创建列表并赋值给变量,变量无需声明(list-Python数据类型之一)
  

[*]
print
(cast) 
#输出cast变量值(print()-Python BIF)
  

[*]
print
(len(cast)) 
#输出cast变量值长度(len()-Python BIF)
  

[*]
print
(cast[
1
]) 
#输出被赋值给cast变量的列表中的第2个元素
  

[*]
cast.append('Gilliam'

#向cast中追加一个元素(append方法是列表自带方法)
  

[*]
cast.pop() #删除列表中最后一个元素,并return最后一个元素
  

[*]
cast.extend(['Gilliam'

'Chapman'
]) 
#向列表末尾追加另一个列表,另一个列表中元素作为目标列表中新元素
  

[*]
cast.remove('Chapman'

#删除列表中指定元素
  

[*]
cast.insert(0

'Chapman'

#向列表中指定位置(此处为第一个元素前)插入一个元素
  




Python代码  





[*]
''
'''列表的迭代'''
  

[*]
  
[*]
movies = ['movie1'

'movie2'

'movie3'

#创建列表并赋值给movies
  

[*]
  
[*]
''
'''for循环是处理列表内个元素的最常用方法
 
[*]
each_movie为目标标示符;movies为列表;print()代码块为列表元素处理代码'''
  

[*]
for
 each_movie 
in
 movies:   

[*]
    print
(each_movie)  

[*]
  
[*]
''
'''while循环是编写迭代代码的另一种备选方法
 
[*]
count 为一个计数标示符,用来表示列表状态信息'''
  

[*]
count = 0
  

[*]
while
 count < len(movies):  

[*]
    print
(movie)  

[*]
    count += 1
  




Python代码  





[*]
movie = [
'The Holy Grail'

1975

'director'

91
,  

[*]
['starring'
,  

[*]
['actor1'

'actor2'

'actor3'
]]] 
#列表内元素可以是各种数据类型,可嵌套
  

[*]
  
[*]
''
'''使用if条件语句和for循环语句输出列表中嵌套的列表,本方法之判断嵌套的第一层列表'''
  

[*]
for
 each_item 
in
 movie:  

[*]
    if
 isinstance
(each_item, list): 
#isinstance()为判断条件,返回true or false;isinstance()为BIF,根据参数判断数据类型
  

[*]
        for
 each_item_deep1 
in
 each_item:   

[*]
            print
(each_item_deep1)  

[*]
    else
:  

[*]
        print
(each_item)  




Python代码  





[*]
''
'''创建一个递归函数解决多层嵌套列表的输出


 

[*]
pring_lol为函数名
 
[*]
the_list为参数'''
  

[*]
  
[*]
movie = ['The Holy Grail'

1975

'director'

91
,  

[*]
['starring'
,  

[*]
['actor1'

'actor2'

'actor3'
]]]  

[*]
  
[*]
def
 print_lol(the_list):  

[*]
    for
 each_item 
in
 the_list:  

[*]
        if
 isinstance(each_item, list):  

[*]
            print_lol(each_item)  
[*]
        else
:  

[*]
            print
(each_item)  

[*]
  
[*]
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代码  





[*]
data = open(filename): 
#打开
  

[*]
print
(data.read()) 
#处理
  

[*]
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代码  





[*]
s = 
'2.33'
  

[*]
help(s.split)  
[*]
  
[*]
import
 os  

[*]
help(os.path.exists)  
[*]
  
[*]
help(open)

  处理异常:




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



基本的异常处理:

Python代码  





[*]
try
:  

[*]
    #尝试执行的代码
  

[*]
except
:  

[*]
    #用于恢复错误的代码
  



  



改进Demo:

Python代码  





[*]
try
:  

[*]
    data = open('sketch.txt'
)  

[*]
  
[*]
    for
 each_line 
in
 data:  

[*]
        try
:  

[*]
            (role, line_spoken) = each_line.split(':'

1
)  

[*]
            print
(role + 
' said: '
 + line_spoken)  

[*]
        except
 ValueError: 
#处理try代码块内特定错误类型的异常
  

[*]
            pass
  

[*]
  
[*]
    data.close() #关闭文件
  

[*]
except

#处理try代码块内所有错误类型的异常
  

[*]
    print
(
'The file is missing'
)  



  



碎碎念:


看了看下一章,貌似有些对文件和异常处理的补充内容。这节课还是初窥。
  =================4.Python第四课-深入文件与异常(数据持久化)



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



Python代码  





[*]
''
'''将上课demo中的谈话内容(conversations)按角色(role)的不同,分别存入两个文本文件中'''
  

[*]
  
[*]
man = [] #分别定义两个list 用来存储两个role的conversations
  

[*]
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'

#通过判断role来确定要存入的list
  

[*]
                man.append(line_spoken)  
[*]
            else
:  

[*]
                other.append(line_spoken)  
[*]
    except
 ValueError:  

[*]
        pass
  

[*]
    data.close() #别忘了完成文件操作关闭数据文件对象
  

[*]
except
 IOError:  

[*]
    print
(
'The file is missing!'
)  

[*]
  
[*]
try
:  

[*]
    man_file = open('man_data.txt'

'w'

#数据文件对象中的文件参数如果不存在,并且相应目录有相应权限,open()会自动创建文件
  

[*]
    other_file = open('other_data.txt'

'w'

# 'w'为文件数据对象的'写'模式
  

[*]
  
[*]
    print
(man, file = man_file) 
#print()函数中的file参数为写入的文件名
  

[*]
    print
(other, file = other_file)  

[*]
  
[*]
    man_file.close() #别忘了完成文件操作关闭数据文件对象
  

[*]
    other_file.close()  
[*]
except
 IOError:  

[*]
    print
(
'File Error!'
)  



  



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




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



改进代码:

Python代码  





[*]
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: 
#将IOError异常对象赋予ioerr变量
  

[*]
    print
(
'File Error :'
 + str(ioerr)) 
#将ioerr转换为字符串类型
  

[*]
  
[*]
try
:  

[*]
    man_file = open('man_data.txt'

'w'
)  

[*]
    other_file = open('other_data.txt'

'w'
)  

[*]
  
[*]
    print
(man, file = man_file)  

[*]
    print
(other, file = other_file)  

[*]
except
 IOError as ioerr:  

[*]
    print
(
'File Error: '
 + str(ioerr))  

[*]
finally

#无论try代码块或者except代码块中的语句是否被执行,finally代码块中的语句
  

[*]
    if
 
'man_file'
 
in
 locals(): 
#判断数据文件对象是否存在,loclas() BIF返回作用域中所有变量的字典
  

[*]
        man_file.close()  
[*]
    if
 
'man_file'
 
in
 locals():  

[*]
        man_file.close()  


  



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




利用with语句,可以将文件处理的代码简化,无需考虑关闭文件,裁剪掉文件异常处理语句中的finally语句。


作用一:简化语法,减少工作量。


作用二:通过逻辑抽象,减少码农脑细胞死亡速度和出错概率。



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

Python代码  





[*]
try
:  

[*]
    with open('man_data.txt'

'w'
) as man_file:  

[*]
        print
(man, file = man_file)  

[*]
    with open('other_data.txt'

'w'
) as other_file:  

[*]
        print
(other, file = other_file)  

[*]
except
 IOError as ioerr:  

[*]
    print
(
'File Error: '
 + str(ioerr))  



  


OR

Python代码  





[*]
try
:  

[*]
    with open('man_data.txt'

'w'
) as man_file, open(
'other_data.txt'

'w'
) as other_file:  

[*]
        print
(man, file = man_file)  

[*]
        print
(other, file = other_file)  

[*]
except
 IOError as ioerr:  

[*]
    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代码  





[*]
''
'''使用pickle模块持久化各种数据类型的数据'''
  

[*]
  
[*]
import
 pickle  

[*]
  
[*]
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'

'wb'
) as man_file, open(
'other_data.txt'

'wb'
) as other_file: 
#由于pickle以二进制模式存储数据,所以我们需要'wb'参数来以二进制方式操作文件
  

[*]
        pickle.dump(man, file = man_file) #dump是pickle中的一个方法,用来写入数据
  

[*]
        pickle.dump(other, file = other_file)  
[*]
except
 IOError as ioerr:  

[*]
    print
(
'File Error: '
 + str(ioerr))  

[*]
except
 pickle.PickleError as perr:  

[*]
    print
(
'Pickling Error: '
 + str(perr)) 
#pickle的异常
  



  



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



Python代码  





[*]
import
 pickle  

[*]
  
[*]
man_data = []  
[*]
  
[*]
try
:  

[*]
    with open('man_file.txt'

'rb'
) as fman: 
#用二进制方式打开文件
  

[*]
        man_data = pickle.load(fman) #pickle中的load方法用于从文件对象中取出数据
  

[*]
except
 IOError as ioerr:  

[*]
    print
(
'File Error: '
 + str(ioerr))  

[*]
except
 pickle.PickleError as perr:  

[*]
    print
(
'Pickling Error: '
 + str(perr))  

[*]
  
[*]
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)



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 = #使用列表推导来取代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)
页: [1]
查看完整版本: 【汇总】python基础