美文网首页Courses
编程基础:Python 学习总结

编程基础:Python 学习总结

作者: Nautilus1 | 来源:发表于2017-09-22 18:11 被阅读0次
    这门课程不是从语法开始,而是通过6个项目串联讲解Python的一些编程思想。从函数的使用、类的使用到创建类。在项目的实现中介绍如何查看阅读Python文档,如何解决bug,Python内置模块、函数的结构等内容。总的来说这门课程是在介绍Python的编程思想而非语法细节。课程地图:

    一、简介

    介绍课程内容,简单的循环、IF语句测试,以及Python的安装。

    二、使用函数

    这部分主要完成两个项目:

    1. 休息一下:写程序安排一天的休息时段
    2. 秘密消息:给文件重命名

    休息一下

    要求每隔一段时间跳出一个页面播放音乐提醒大家休息。
    解决这个问题的思路是:
    Repeat{

    1. 等待2小时
    2. 打开浏览器
      }

    代码很简单,主要是学到库 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
    

    秘密消息

    要求对文件夹下的所有图片重命名,显示隐藏的信息。
    解决思路:

    1. 得到文件夹下所有的文件名
    2. 对每个文件重命名

    主要学习文件操作。

    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()              #输出当前操作目录
        #切换当前操作目录。按理说file_list 已经存了所有文件名,在不在prank文件夹下都可以对其遍历。但是重命名操作需要定位文件所在位置。
        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'))         #需要定位到文件所在位置
    

    目前用于解决问题的方法都是建文件写函数逐行写执行操作,但是函数也有不能完成的任务——电影展示:同一个模板不同的对象使用,重复代码显然不是好方法。

    三、使用类

    1. 画乌龟

    画一圈正方形形成一个圆。结果如图

    turtle是Python中一个绘制图像的函数库,好像一只乌龟在坐标系上爬行,用路径构成所画图像。

    import turtle
    #画方形
    def draw_square(t):
        for i in range(1,5):
            t.forward(100)
            t.right(90)       #右转90度,每次以爬行前进方向确定左右。
            #t.right(60)
            
    #画图主要实现函数
    def draw_art():
        #定义画布
        window = turtle.Screen()
        window.bgcolor('green')
    
        #create turtle brad, draw a square
        brad = turtle.Turtle()          #使用turtle类生成实例对象
        brad.shape("turtle")
        brad.color("yellow")
        brad.speed(2)
        
        for i in range(1,37):
            draw_square(brad)
            brad.right(10)
        
        #产生另一个实例画圆
        angie = turtle.Turtle()
        angie.shape('arrow')
        angie.color("blue")
        angie.circle(100)
        
        window.exitonclick()
    
    输出结果:

    这个例子主要是为了引入类的概念,改进一下可以画出很多有趣的图形。如分形树:

    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)#沿着当前的方向画画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 调整画笔
     
        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. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
        #否则turtle一移动就会自动的把线画出来
     
        #t = tree([p], 200, 65, 0.6375)
        t = tree([p], 200, 65, 0.6375)
         
    main()
    

    时钟程序:

    import turtle  
    from datetime import *  
       
    # 抬起画笔,向前运动一段距离放下  
    def Skip(step):  
        turtle.penup()  
        turtle.forward(step)  
        turtle.pendown()  
       
    def mkHand(name, length):  
        # 注册Turtle形状,建立表针Turtle  
        turtle.reset()  
        Skip(-length * 0.1)  
        # 开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。  
        turtle.begin_poly()  
        turtle.forward(length * 1.1)  
        # 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。  
        turtle.end_poly()  
        # 返回最后记录的多边形。  
        handForm = turtle.get_poly()  
        turtle.register_shape(name, handForm)  
       
    def Init():  
        global secHand, minHand, hurHand, printer  
        # 重置Turtle指向北  
        turtle.mode("logo")  
        # 建立三个表针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()  
        # 隐藏画笔的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():  
        # 绘制表针的动态显示  
        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后继续调用tick  
        turtle.ontimer(Tick, 100)  
       
    def main():  
        # 打开/关闭龟动画,并为更新图纸设置延迟。  
        turtle.tracer(False)  
        Init()  
        SetupClock(160)  
        turtle.tracer(True)  
        Tick()  
        turtle.mainloop()  
       
    if __name__ == "__main__":  
        main()
    

    2. 发送消息

    使用Twilio模块发短信到手机。主要介绍Python类、模块、函数的关系,from关键字的使用。

    3. 冒犯语检测器

    检测一段文本中是否含有冒犯语。
    解决思路:

    1. 从文档中读取文本
    2. 检查这段文本是否有冒犯语

    本来以为检测冒犯语的步骤会使用字符串查找匹配的方式,课程简化为丢给网页处理。主要还是文件的处理和标准库中urllib的调用。

    import urllib
    
    def read_text():
        #quotes就是文件这个类的一个实例
        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()
    

    四、创造类

    写一个电影网页,展示一些电影的海报,可播放其预告片。
    首先是电影类的定义,放在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):
            #播放预告片
            webbrowser.open(self.trailer_youtube_url)
    
    介绍了如何给函数写文档,如何定义类属性和函数。

    然后导入这个模块生成对应实例,调用fresh_tomatoes模快生成网页。

    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" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">
        <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)
    

    最后介绍了下继承、函数重写覆盖等概念,跑一遍例子就都清楚了。

    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()
    
    参考:

    分形树
    时钟

    相关文章

      网友评论

        本文标题:编程基础:Python 学习总结

        本文链接:https://www.haomeiwen.com/subject/tpnxextx.html