Python爬蟲與數據分析之進階教程:文件操做、lambda表達式、遞歸、yield生成器

專欄目錄:html

Python爬蟲與數據分析之python教學視頻、python源碼分享,pythonpython

Python爬蟲與數據分析之基礎教程:Python的語法、字典、元組、列表linux

Python爬蟲與數據分析之進階教程:文件操做、lambda表達式、遞歸、yield生成器正則表達式

Python爬蟲與數據分析之模塊:內置模塊、開源模塊、自定義模塊算法

Python爬蟲與數據分析之爬蟲技能:urlib庫、xpath選擇器、正則表達式sql

Python爬蟲與數據分析之京東爬蟲實戰:爬取京東商品並存入sqlite3數據庫數據庫

Python爬蟲與數據分析之python開源爬蟲項目彙總編程

 

python經常使用內置函數:windows

 

 

文件操做

操做文件時,通常須要經歷以下步驟:數組

  • 打開文件
  • 操做文件
  • 關閉文件

1、打開文件

1

文件句柄 = file('文件路徑', '模式')

注:python中打開文件有兩種方式,即:open(...)  file(...) ,本質上前者在內部會調用後者來進行文件操做,推薦使用 open

打開文件時,須要指定文件路徑和以何等方式打開文件,打開後,便可獲取該文件句柄,往後經過此文件句柄對該文件操做。

打開文件的模式有:

  • r,只讀模式(默認)。
  • w,只寫模式。【不可讀;不存在則建立;存在則刪除內容;】
  • a,追加模式。【可讀;   不存在則建立;存在則只追加內容;】

"+" 表示能夠同時讀寫某個文件

  • r+,可讀寫文件。【可讀;可寫;可追加】
  • w+,寫讀
  • a+,同a

"U"表示在讀取時,能夠將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)

  • rb
  • wb
  • ab

2、操做函數

 1 class file(object):
 2   
 3     def close(self): # real signature unknown; restored from __doc__
 4         關閉文件
 5         """
 6         close() -> None or (perhaps) an integer.  Close the file.
 7          
 8         """
 9  
10     def fileno(self): # real signature unknown; restored from __doc__
11         文件描述符  
12          """
13         fileno() -> integer "file descriptor".
14          
15         This is needed for lower-level file interfaces, such os.read().
16         """
17         return 0    
18  
19     def flush(self): # real signature unknown; restored from __doc__
20         刷新文件內部緩衝區
21         """ flush() -> None.  Flush the internal I/O buffer. """
22         pass
23  
24  
25     def isatty(self): # real signature unknown; restored from __doc__
26         判斷文件是不是贊成tty設備
27         """ isatty() -> true or false.  True if the file is connected to a tty device. """
28         return False
29  
30  
31     def next(self): # real signature unknown; restored from __doc__
32         獲取下一行數據,不存在,則報錯
33         """ x.next() -> the next value, or raise StopIteration """
34         pass
35  
36     def read(self, size=None): # real signature unknown; restored from __doc__
37         讀取指定字節數據
38         """
39         read([size]) -> read at most size bytes, returned as a string.
40          
41         """
42         pass
43  
44     def readinto(self): # real signature unknown; restored from __doc__
45         讀取到緩衝區,不要用,將被遺棄
46         """ readinto() -> Undocumented.  Don't use this; it may go away. """
47         pass
48  
49     def readline(self, size=None): # real signature unknown; restored from __doc__
50         僅讀取一行數據
51         """
52         readline([size]) -> next line from the file, as a string.
53          """
54         pass
55  
56     def readlines(self, size=None): # real signature unknown; restored from __doc__
57         讀取全部數據,並根據換行保存值列表
58         """
59         readlines([size]) -> list of strings, each a line from the file.
60         """
61         return []
62  
63     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
64         指定文件中指針位置
65         """
66         seek(offset[, whence]) -> None.  Move to new file position.
67         """
68         pass
69  
70     def tell(self): # real signature unknown; restored from __doc__
71         獲取當前指針位置
72         """ tell() -> current file position, an integer (may be a long integer). """
73         pass
74  
75     def truncate(self, size=None): # real signature unknown; restored from __doc__
76         截斷數據,僅保留指定以前數據
77         """
78         pass
79  
80     def write(self, p_str): # real signature unknown; restored from __doc__
81         寫內容
82         """
83         write(str) -> None.  Write string str to file.
84         """
85         pass
86  
87     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
88         將一個字符串列表寫入文件
89         """
90         writelines(sequence_of_strings) -> None.  Write the strings to the file.
91         """
92         pass
93  
94     def xreadlines(self): # real signature unknown; restored from __doc__
95         可用於逐行讀取文件,非所有
96         """
97         xreadlines() -> returns self.
98         """
99         pass
View Code

 

3、with

爲了不打開文件後忘記關閉,能夠經過管理上下文,即:

1

2

3

with open('log','r') as f:     

    ...

如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。

在Python 2.7 後,with又支持同時對多個文件的上下文進行管理,即:

1

2

with open('log1') as obj1, open('log2') as obj2:

    pass

 

4、python文件操做實例

自定義函數

1、背景

在學習函數以前,一直遵循:面向過程編程,即:根據業務邏輯從上到下實現功能,其每每用一長段代碼來實現指定功能,開發過程當中最多見的操做就是粘貼複製,也就是將以前實現的代碼塊複製到現需功能處,以下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

while True:

    if cpu利用率 > 90%:

        #發送郵件提醒

        鏈接郵箱服務器

        發送郵件

        關閉鏈接

  

    if 硬盤使用空間 > 90%:

        #發送郵件提醒

        鏈接郵箱服務器

        發送郵件

        關閉鏈接

  

    if 內存佔用 > 80%:

        #發送郵件提醒

        鏈接郵箱服務器

        發送郵件

        關閉鏈接

腚眼一看上述代碼,if條件語句下的內容能夠被提取出來公用,以下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

def 發送郵件(內容)

    #發送郵件提醒

    鏈接郵箱服務器

    發送郵件

    關閉鏈接

  

while True:

  

    if cpu利用率 > 90%:

        發送郵件('CPU報警')

  

    if 硬盤使用空間 > 90%:

        發送郵件('硬盤報警')

  

    if 內存佔用 > 80%:

對於上述的兩種實現方式,第二次必然比第一次的重用性和可讀性要好,其實這就是函數式編程和麪向過程編程的區別:

  • 函數式:將某功能代碼封裝到函數中,往後便無需重複編寫,僅調用函數便可
  • 面向對象:對函數進行分類和封裝,讓開發「更快更好更強...」

函數式編程最重要的是加強代碼的重用性和可讀性

2、 函數的定義和使用

1

2

3

4

5

def 函數名(參數):

     

    ...

    函數體

    ...

函數的定義主要有以下要點:

  • def:表示函數的關鍵字
  • 函數名:函數的名稱,往後根據函數名調用函數
  • 函數體:函數中進行一系列的邏輯計算,如:發送郵件、計算出 [11,22,38,888,2]中的最大數等...
  • 參數:爲函數體提供數據
  • 返回值:當函數執行完畢後,能夠給調用者返回數據。

以上要點中,比較重要有參數和返回值:

一、返回值

函數是一個功能塊,該功能到底執行成功與否,須要經過返回值來告知調用者。

二、參數

函數的有三中不一樣的參數:

  • 普通參數
  • 默認參數
  • 動態參數

 View Code

 

lambda表達式

學習條件運算時,對於簡單的 if else 語句,能夠使用三元運算來表示,即:

1

2

3

4

5

6

7

8

# 普通條件語句

if 1 == 1:

    name = 'wupeiqi'

else:

    name = 'alex'

  

# 三元運算

name = 'wupeiqi' if 1 == 1 else 'alex'

對於簡單的函數,也存在一種簡便的表示方式,即:lambda表達式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

# ###################### 普通函數 ######################

# 定義函數(普通方式)

def func(arg):

    return arg + 1

  

# 執行函數

result = func(123)

  

# ###################### lambda ######################

  

# 定義函數(lambda表達式)

my_lambda = lambda arg : arg + 1

  

# 執行函數

result = my_lambda(123)

lambda存在乎義就是對簡單函數的簡潔表示

內置函數 二

1、map

遍歷序列,對序列中每一個元素進行操做,最終獲取新的序列。

 

1 li = [11, 22, 33]
2  
3 new_list = map(lambda a: a + 100, li)
4  
5 
6 li = [11, 22, 33]
7 sl = [1, 2, 3]
8 new_list = map(lambda a, b: a + b, li, sl)
View Code

 

2、filter

對於序列中的元素進行篩選,最終獲取符合條件的序列

1  
2 li = [11, 22, 33]
3  
4 new_list = filter(lambda arg: arg > 22, li)
5  
6 #filter第一個參數爲空,將獲取原來序列
View Code

 

3、reduce

對於序列內全部元素進行累計操做

 

li = [11, 22, 33]
 
result = reduce(lambda arg1, arg2: arg1 + arg2, li)
 
# reduce的第一個參數,函數必需要有兩個參數
# reduce的第二個參數,要循環的序列
# reduce的第三個參數,初始值
View Code

 

yield生成器

一、對比range 和 xrange 的區別

1

2

3

4

>>> print range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> print xrange(10)

xrange(10)

如上代碼所示,range會在內存中建立全部指定的數字,而xrange不會當即建立,只有在迭代循環時,纔去建立每一個數組。

 

1 def nrange(num):
2     temp = -1
3     while True:
4         temp = temp + 1
5         if temp >= num:
6             return
7         else:
8             yield temp
View Code

 

二、文件操做的 read 和 xreadlinex 的的區別

1

2

read會讀取全部內容到內存

xreadlines則只有在循環迭代時才獲取

 

 1 def NReadlines():
 2     with open('log','r') as f:
 3         while True:
 4             line = f.next()
 5             if line:
 6                 yield line
 7             else:
 8                 return
 9  
10 for i in NReadlines():
11     print i
12  
13 
14  def NReadlines():
15     with open('log','r') as f:
16         seek = 0
17         while True:
18             f.seek(seek)
19             data = f.readline()
20             if data:
21                 seek = f.tell()
22                 yield data
23             else:
24                 return
25  
26 for item in NReadlines():
27     print item
28  
View Code

 

 裝飾器

裝飾器是函數,只不過該函數能夠具備特殊的含義,裝飾器用來裝飾函數或類,使用裝飾器能夠在函數執行前和執行後添加相應操做。

1

2

3

4

5

6

7

8

9

10

def wrapper(func):

    def result():

        print 'before'

        func()

        print 'after'

    return result

 

@wrapper

def foo():

    print 'foo'

 

 1 import functools
 2  
 3  
 4 def wrapper(func):
 5     @functools.wraps(func)
 6     def wrapper():
 7         print 'before'
 8         func()
 9         print 'after'
10     return wrapper
11  
12 @wrapper
13 def foo():
14     print 'foo'
15  
16 
17 #!/usr/bin/env python
18 #coding:utf-8
19  
20 def Before(request,kargs):
21     print 'before'
22      
23 def After(request,kargs):
24     print 'after'
25  
26  
27 def Filter(before_func,after_func):
28     def outer(main_func):
29         def wrapper(request,kargs):
30              
31             before_result = before_func(request,kargs)
32             if(before_result != None):
33                 return before_result;
34              
35             main_result = main_func(request,kargs)
36             if(main_result != None):
37                 return main_result;
38              
39             after_result = after_func(request,kargs)
40             if(after_result != None):
41                 return after_result;
42              
43         return wrapper
44     return outer
45      
46 @Filter(Before, After)
47 def Index(request,kargs):
48     print 'index'
49      
50      
51 if __name__ == '__main__':
52     Index(1,2)
53  
View Code

 

冒泡算法

需求:請按照從小到大對列表 [13, 22, 6, 99, 11] 進行排序

思路:相鄰兩個值進行比較,將較大的值放在右側,依次比較!

 

 1  li = [13, 22, 6, 99, 11]
 2  
 3 for m in range(4):     # 等價於 #for m in range(len(li)-1):
 4     if li[m]> li[m+1]:
 5         temp = li[m+1]
 6         li[m+1] = li[m]
 7         li[m] = temp
 8   
 9 
10 li = [13, 22, 6, 99, 11]
11  
12 for m in range(4):     # 等價於 #for m in range(len(li)-1):
13     if li[m]> li[m+1]:
14         temp = li[m+1]
15         li[m+1] = li[m]
16         li[m] = temp
17  
18 for m in range(3):     # 等價於 #for m in range(len(li)-2):
19     if li[m]> li[m+1]:
20         temp = li[m+1]
21         li[m+1] = li[m]
22         li[m] = temp
23  
24 for m in range(2):     # 等價於 #for m in range(len(li)-3):
25     if li[m]> li[m+1]:
26         temp = li[m+1]
27         li[m+1] = li[m]
28         li[m] = temp
29  
30 for m in range(1):     # 等價於 #for m in range(len(li)-4):
31     if li[m]> li[m+1]:
32         temp = li[m+1]
33         li[m+1] = li[m]
34         li[m] = temp
35 print li
36  
37 
38 li = [13, 22, 6, 99, 11]
39  
40 for i in range(1,5):
41     for m in range(len(li)-i): 
42         if li[m] > li[m+1]:
43             temp = li[m+1]
44             li[m+1] = li[m]
45             li[m] = temp
46  
View Code

 

遞歸

利用函數編寫以下數列:

斐波那契數列指的是這樣一個數列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368

 

1 def func(arg1,arg2):
2     if arg1 == 0:
3         print arg1, arg2
4     arg3 = arg1 + arg2
5     print arg3
6     func(arg2, arg3)
7  
8 func(0,1)
View Code

 

 

公告

更多python源碼,視頻教程,歡迎關注公衆號:南城故夢

>零起點大數據與量化分析PDF及教程源碼
>利用python進行數據分析PDF及配套源碼
>大數據項目實戰之Python金融應用編程(數據分析、訂價與量化投資)講義及源碼
>董付國老師Python教學視頻
1. 課堂教學管理系統開發:在線考試功能設計與實現
2. Python+pillow圖像編程;
3. Python+Socket編程
4. Python+tkinter開發;
5. Python數據分析與科學計算可視化
6. Python文件操做
7. Python多線程與多進程編程
8. Python字符串與正則表達式
.....

>數據分析教學視頻
1. 輕鬆駕馭統計學——數據分析必備技能(12集);
2. 輕鬆上手Tableau 軟件——讓數據可視化(9集);
3. 競品分析實戰攻略(6集);
4. 電商數據化運營——三大數據化工具應用(20集);

>大數據(視頻與教案)
1. hadoop
2. Scala
3. spark

>Python網絡爬蟲分享系列教程PDF

>【千鋒】Python爬蟲從入門到精通(精華版)(92集)

歡迎關注公衆號獲取學習資源:南城故夢

相關文章
相關標籤/搜索