編程基礎(chǔ):Python 學(xué)習(xí)總結(jié)

這門(mén)課程不是從語(yǔ)法開(kāi)始,而是通過(guò)6個(gè)項(xiàng)目串聯(lián)講解Python的一些編程思想。從函數(shù)的使用、類(lèi)的使用到創(chuàng)建類(lèi)。在項(xiàng)目的實(shí)現(xiàn)中介紹如何查看閱讀Python文檔,如何解決bug,Python內(nèi)置模塊、函數(shù)的結(jié)構(gòu)等內(nèi)容。總的來(lái)說(shuō)這門(mén)課程是在介紹Python的編程思想而非語(yǔ)法細(xì)節(jié)。課程地圖:

一、簡(jiǎn)介

介紹課程內(nèi)容,簡(jiǎn)單的循環(huán)、IF語(yǔ)句測(cè)試,以及Python的安裝。

二、使用函數(shù)

這部分主要完成兩個(gè)項(xiàng)目:

  1. 休息一下:寫(xiě)程序安排一天的休息時(shí)段
  2. 秘密消息:給文件重命名

休息一下

要求每隔一段時(shí)間跳出一個(gè)頁(yè)面播放音樂(lè)提醒大家休息。
解決這個(gè)問(wèn)題的思路是:
Repeat{

  1. 等待2小時(shí)
  2. 打開(kāi)瀏覽器
    }

代碼很簡(jiǎn)單,主要是學(xué)到庫(kù) webbrowser

import time
import webbrowser
total = 3
count = 0
print 'this program started on ' + time.ctime()
while(count < total):
    time.sleep(10)
    webbrowser.open('https://classroom.udacity.com')
    count += 1

秘密消息

要求對(duì)文件夾下的所有圖片重命名,顯示隱藏的信息。
解決思路:

  1. 得到文件夾下所有的文件名
  2. 對(duì)每個(gè)文件重命名

主要學(xué)習(xí)文件操作。

import os
import string
def rename_files():

    #1.get file names from a floder
    file_list = os.listdir('/home/nimo/Course/PythonU/prank')
    #print os.getcwd()              #輸出當(dāng)前操作目錄
    #切換當(dāng)前操作目錄。按理說(shuō)file_list 已經(jīng)存了所有文件名,在不在prank文件夾下都可以對(duì)其遍歷。但是重命名操作需要定位文件所在位置。
    os.chdir('/home/nimo/Course/PythonU/prank')              

    #2.for each file,rename filename
    for file_name in file_list:
        print "old name:",file_name
        print "new name:",file_name.translate(None,'0123456789')
        os.rename(file_name,file_name.translate(None,'0123456789'))         #需要定位到文件所在位置

目前用于解決問(wèn)題的方法都是建文件寫(xiě)函數(shù)逐行寫(xiě)執(zhí)行操作,但是函數(shù)也有不能完成的任務(wù)——電影展示:同一個(gè)模板不同的對(duì)象使用,重復(fù)代碼顯然不是好方法。

三、使用類(lèi)

1. 畫(huà)烏龜

畫(huà)一圈正方形形成一個(gè)圓。結(jié)果如圖

turtle是Python中一個(gè)繪制圖像的函數(shù)庫(kù),好像一只烏龜在坐標(biāo)系上爬行,用路徑構(gòu)成所畫(huà)圖像。

import turtle
#畫(huà)方形
def draw_square(t):
    for i in range(1,5):
        t.forward(100)
        t.right(90)       #右轉(zhuǎn)90度,每次以爬行前進(jìn)方向確定左右。
        #t.right(60)
        
#畫(huà)圖主要實(shí)現(xiàn)函數(shù)
def draw_art():
    #定義畫(huà)布
    window = turtle.Screen()
    window.bgcolor('green')

    #create turtle brad, draw a square
    brad = turtle.Turtle()          #使用turtle類(lèi)生成實(shí)例對(duì)象
    brad.shape("turtle")
    brad.color("yellow")
    brad.speed(2)
    
    for i in range(1,37):
        draw_square(brad)
        brad.right(10)
    
    #產(chǎn)生另一個(gè)實(shí)例畫(huà)圓
    angie = turtle.Turtle()
    angie.shape('arrow')
    angie.color("blue")
    angie.circle(100)
    
    window.exitonclick()

輸出結(jié)果:

這個(gè)例子主要是為了引入類(lèi)的概念,改進(jìn)一下可以畫(huà)出很多有趣的圖形。如分形樹(shù):

from turtle import Turtle, mainloop
 
def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿著當(dāng)前的方向畫(huà)畫(huà)Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#將元素增加到列表的最后
            lst.append(q)
        tree(lst, l*f, a, f)
   
def main():
    p = Turtle()
    p.color("green")
    p.pensize(5)
    #p.setundobuffer(None)
    p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
    #because hiding the turtle speeds up the drawing observably.
    #p.speed(10)
   # p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
    p.speed(10)
    #TurtleScreen methods can then be called for that object.
    p.left(90)# Turn turtle left by angle units. direction 調(diào)整畫(huà)筆
 
    p.penup() #Pull the pen up – no drawing when moving.
    p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
    p.pendown()# Pull the pen down – drawing when moving. 這三條語(yǔ)句是一個(gè)組合相當(dāng)于先把筆收起來(lái)再移動(dòng)到指定位置,再把筆放下開(kāi)始畫(huà)
    #否則turtle一移動(dòng)就會(huì)自動(dòng)的把線畫(huà)出來(lái)
 
    #t = tree([p], 200, 65, 0.6375)
    t = tree([p], 200, 65, 0.6375)
     
main()

時(shí)鐘程序:

import turtle  
from datetime import *  
   
# 抬起畫(huà)筆,向前運(yùn)動(dòng)一段距離放下  
def Skip(step):  
    turtle.penup()  
    turtle.forward(step)  
    turtle.pendown()  
   
def mkHand(name, length):  
    # 注冊(cè)Turtle形狀,建立表針Turtle  
    turtle.reset()  
    Skip(-length * 0.1)  
    # 開(kāi)始記錄多邊形的頂點(diǎn)。當(dāng)前的烏龜位置是多邊形的第一個(gè)頂點(diǎn)。  
    turtle.begin_poly()  
    turtle.forward(length * 1.1)  
    # 停止記錄多邊形的頂點(diǎn)。當(dāng)前的烏龜位置是多邊形的最后一個(gè)頂點(diǎn)。將與第一個(gè)頂點(diǎn)相連。  
    turtle.end_poly()  
    # 返回最后記錄的多邊形。  
    handForm = turtle.get_poly()  
    turtle.register_shape(name, handForm)  
   
def Init():  
    global secHand, minHand, hurHand, printer  
    # 重置Turtle指向北  
    turtle.mode("logo")  
    # 建立三個(gè)表針Turtle并初始化  
    mkHand("secHand", 135)  
    mkHand("minHand", 125)  
    mkHand("hurHand", 90)  
    secHand = turtle.Turtle()  
    secHand.shape("secHand")  
    minHand = turtle.Turtle()  
    minHand.shape("minHand")  
    hurHand = turtle.Turtle()  
    hurHand.shape("hurHand")  
     
    for hand in secHand, minHand, hurHand:  
        hand.shapesize(1, 1, 3)  
        hand.speed(0)  
     
    # 建立輸出文字Turtle  
    printer = turtle.Turtle()  
    # 隱藏畫(huà)筆的turtle形狀  
    printer.hideturtle()  
    printer.penup()  
      
def SetupClock(radius):  
    # 建立表的外框  
    turtle.reset()  
    turtle.pensize(7)  
    for i in range(60):  
        Skip(radius)  
        if i % 5 == 0:  
            turtle.forward(20)  
            Skip(-radius - 20)  
             
            Skip(radius + 20)  
            if i == 0:  
                turtle.write(int(12), align="center", font=("Courier", 14, "bold"))  
            elif i == 30:  
                Skip(25)  
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))  
                Skip(-25)  
            elif (i == 25 or i == 35):  
                Skip(20)  
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))  
                Skip(-20)  
            else:  
                turtle.write(int(i/5), align="center", font=("Courier", 14, "bold"))  
            Skip(-radius - 20)  
        else:  
            turtle.dot(5)  
            Skip(-radius)  
        turtle.right(6)  
          
def Week(t):     
    week = ["星期一", "星期二", "星期三",  
            "星期四", "星期五", "星期六", "星期日"]  
    return week[t.weekday()]  
   
def Date(t):  
    y = t.year  
    m = t.month  
    d = t.day  
    return "%s %d%d" % (y, m, d)  
   
def Tick():  
    # 繪制表針的動(dòng)態(tài)顯示  
    t = datetime.today()  
    second = t.second + t.microsecond * 0.000001  
    minute = t.minute + second / 60.0  
    hour = t.hour + minute / 60.0  
    secHand.setheading(6 * second)  
    minHand.setheading(6 * minute)  
    hurHand.setheading(30 * hour)  
      
    turtle.tracer(False)   
    printer.forward(65)  
    printer.write(Week(t), align="center",  
                  font=("Courier", 14, "bold"))  
    printer.back(130)  
    printer.write(Date(t), align="center",  
                  font=("Courier", 14, "bold"))  
    printer.home()  
    turtle.tracer(True)  
   
    # 100ms后繼續(xù)調(diào)用tick  
    turtle.ontimer(Tick, 100)  
   
def main():  
    # 打開(kāi)/關(guān)閉龜動(dòng)畫(huà),并為更新圖紙?jiān)O(shè)置延遲。  
    turtle.tracer(False)  
    Init()  
    SetupClock(160)  
    turtle.tracer(True)  
    Tick()  
    turtle.mainloop()  
   
if __name__ == "__main__":  
    main()

2. 發(fā)送消息

使用Twilio模塊發(fā)短信到手機(jī)。主要介紹Python類(lèi)、模塊、函數(shù)的關(guān)系,from關(guān)鍵字的使用。

3. 冒犯語(yǔ)檢測(cè)器

檢測(cè)一段文本中是否含有冒犯語(yǔ)。
解決思路:

  1. 從文檔中讀取文本
  2. 檢查這段文本是否有冒犯語(yǔ)

本來(lái)以為檢測(cè)冒犯語(yǔ)的步驟會(huì)使用字符串查找匹配的方式,課程簡(jiǎn)化為丟給網(wǎng)頁(yè)處理。主要還是文件的處理和標(biāo)準(zhǔn)庫(kù)中urllib的調(diào)用。

import urllib

def read_text():
    #quotes就是文件這個(gè)類(lèi)的一個(gè)實(shí)例
    quotes = open('/home/nimo/Course/PythonU/2/movie_quotes.txt')
    contents_of_file = quotes.read()
    #print contents_of_file
    quotes.close()
    check_profanity(contents_of_file)
    
def check_profanity(text_to_check):
    connection = urllib.urlopen('http://www.wdylike.appspot.com/?q=' + text_to_check)
    output = connection.read()
    print output
    connection.close()

四、創(chuàng)造類(lèi)

寫(xiě)一個(gè)電影網(wǎng)頁(yè),展示一些電影的海報(bào),可播放其預(yù)告片。
首先是電影類(lèi)的定義,放在media.py模快:

import webbrowser

class Movie():
    '''This class provides a way to store movie related information'''
    VALID_RATINGS = ['G', 'PG', 'PG-13', 'R']
    
    def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
        self.title = movie_title
        self.storyline = movie_storyline
        self.poster_image_url = movie_storyline
        self.trailer_youtube_url = trailer_youtube
        
    def show_trailer(self):
        #播放預(yù)告片
        webbrowser.open(self.trailer_youtube_url)

介紹了如何給函數(shù)寫(xiě)文檔,如何定義類(lèi)屬性和函數(shù)。

然后導(dǎo)入這個(gè)模塊生成對(duì)應(yīng)實(shí)例,調(diào)用fresh_tomatoes模快生成網(wǎng)頁(yè)。

import media
import fresh_tomatoes

toy_story = media.Movie('Toy Story',
                        'A story of a boy and his toys that come to life',
                        'https://movie.douban.com/photos/photo/523015829/',
                        'http://www.le.com/ptv/vplay/26876125.html?ch=baiduald_mfdy')
                        
#print toy_story.storyline

avatar = media.Movie('avatar',
                     'A marine on an alien planet',
                     'https://movie.douban.com/photos/photo/492458287/',
                     '')
                     
school_of_rock = media.Movie('school_of_rock',
                     'storyline',
                     'https://movie.douban.com/photos/photo/2193668557/',
                     '')
                     
ratatouille = media.Movie('ratatouille',
                     'storyline',
                     'https://movie.douban.com/photos/photo/2151385036/',
                     '')
                     
midnight_in_paris = media.Movie('midnight_in_paris',
                     'storyline',
                     'https://movie.douban.com/photos/photo/944234798/',
                     '')    
                     
hunger_games = media.Movie('hunger_games',
                     'storyline',
                     'https://movie.douban.com/photos/photo/1460591675/',
                     '')                 

movies = [toy_story, avatar, school_of_rock, ratatouille, midnight_in_paris, hunger_games]
fresh_tomatoes.open_movies_page(movies)
#print media.Movie.__name__, media.Movie.__module__
import webbrowser
import os
import re

# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Fresh Tomatoes!</title>
    <!-- Bootstrap 3 -->
    <link rel="stylesheet" >
    <link rel="stylesheet" >
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
    <style type="text/css" media="screen">
        body {
            padding-top: 80px;
        }
        #trailer .modal-dialog {
            margin-top: 200px;
            width: 640px;
            height: 480px;
        }
        .hanging-close {
            position: absolute;
            top: -12px;
            right: -12px;
            z-index: 9001;
        }
        #trailer-video {
            width: 100%;
            height: 100%;
        }
        .movie-tile {
            margin-bottom: 20px;
            padding-top: 20px;
        }
        .movie-tile:hover {
            background-color: #EEE;
            cursor: pointer;
        }
        .scale-media {
            padding-bottom: 56.25%;
            position: relative;
        }
        .scale-media iframe {
            border: none;
            height: 100%;
            position: absolute;
            width: 100%;
            left: 0;
            top: 0;
            background-color: white;
        }
    </style>
    <script type="text/javascript" charset="utf-8">
        // Pause the video when the modal is closed
        $(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {
            // Remove the src so the player itself gets removed, as this is the only
            // reliable way to ensure the video stops playing in IE
            $("#trailer-video-container").empty();
        });
        // Start playing the video whenever the trailer modal is opened
        $(document).on('click', '.movie-tile', function (event) {
            var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
            var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';
            $("#trailer-video-container").empty().append($("<iframe></iframe>", {
              'id': 'trailer-video',
              'type': 'text-html',
              'src': sourceUrl,
              'frameborder': 0
            }));
        });
        // Animate in the movies when the page loads
        $(document).ready(function () {
          $('.movie-tile').hide().first().show("fast", function showNext() {
            $(this).next("div").show("fast", showNext);
          });
        });
    </script>
</head>
'''

# The main page layout and title bar
main_page_content = '''
  <body>
    <!-- Trailer Video Modal -->
    <div class="modal" id="trailer">
      <div class="modal-dialog">
        <div class="modal-content">
          <a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">
            ![](https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24)
          </a>
          <div class="scale-media" id="trailer-video-container">
          </div>
        </div>
      </div>
    </div>
    <!-- Main Page Content -->
    <div class="container">
      <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
          <div class="navbar-header">
            <a class="navbar-brand" href="#">Fresh Tomatoes Movie Trailers</a>
          </div>
        </div>
      </div>
    </div>
    <div class="container">
      {movie_tiles}
    </div>
  </body>
</html>
'''

# A single movie entry html template
movie_tile_content = '''
<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">
    ![]({poster_image_url})
    <h2>{movie_title}</h2>
</div>
'''

def create_movie_tiles_content(movies):
    # The HTML content for this section of the page
    content = ''
    for movie in movies:
        # Extract the youtube ID from the url
        youtube_id_match = re.search(
            r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
        youtube_id_match = youtube_id_match or re.search(
            r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
        trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
                              else None)

        # Append the tile for the movie with its content filled in
        content += movie_tile_content.format(
            movie_title=movie.title,
            poster_image_url=movie.poster_image_url,
            trailer_youtube_id=trailer_youtube_id
        )
    return content


def open_movies_page(movies):
    # Create or overwrite the output file
    output_file = open('fresh_tomatoes.html', 'w')

    # Replace the movie tiles placeholder generated content
    rendered_content = main_page_content.format(
        movie_tiles=create_movie_tiles_content(movies))

    # Output the file
    output_file.write(main_page_head + rendered_content)
    output_file.close()

    # open the output file in the browser (in a new tab, if possible)
    url = os.path.abspath(output_file.name)
    webbrowser.open('file://' + url, new=2)

最后介紹了下繼承、函數(shù)重寫(xiě)覆蓋等概念,跑一遍例子就都清楚了。

class Parent():
    def __init__(self, last_name, eye_color):
        print 'Parent Constructor Called'
        self.last_name = last_name
        self.eye_color = eye_color
    
    def show_info(self):
        print 'last name:',self.last_name
        print 'eye color:',self.eye_color
        
class Child(Parent):
    def __init__(self, last_name, eye_color, number_of_toys):
        print 'Child Constructor Called'
        Parent.__init__(self, last_name, eye_color)
        self.number_of_toys = number_of_toys
        
    def show_info(self):
        print 'last name:',self.last_name
        print 'eye color:',self.eye_color
        print 'number_of_toys:',str(self.number_of_toys)
        
andy_cycus = Child('cycus', 'blue', 5)
#print andy_cycus.last_name, andy_cycus.number_of_toys
andy_cycus.show_info()
參考:

分形樹(shù)
時(shí)鐘

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • http://python.jobbole.com/85231/ 關(guān)于專(zhuān)業(yè)技能寫(xiě)完項(xiàng)目接著寫(xiě)寫(xiě)一名3年工作經(jīng)驗(yàn)的J...
    燕京博士閱讀 7,630評(píng)論 1 118
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個(gè) Awesome - XXX 系列...
    aimaile閱讀 26,593評(píng)論 6 427
  • 前言 ||| 第二章 使用ArcPy編寫(xiě)腳本 Python支持大部分在其他語(yǔ)言中出現(xiàn)的編程結(jié)構(gòu)。在本章內(nèi)容中,我們...
    muyan閱讀 90,239評(píng)論 10 55
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,523評(píng)論 25 708
  • 這個(gè)周末,茶山入住了上海的金門(mén)大酒店,它位于上海南京路步行街附近,雖然不起眼,但據(jù)稱,這個(gè)酒店已經(jīng)有超過(guò)100年的...
    茶山閱讀 224評(píng)論 0 2