一、簡介
介紹課程內容,簡單的循環、IF語句測試,以及Python的安裝。
二、使用函數
這部分主要完成兩個項目:
- 休息一下:寫程序安排一天的休息時段
- 秘密消息:給文件重命名
休息一下
要求每隔一段時間跳出一個頁面播放音樂提醒大家休息。
解決這個問題的思路是:
Repeat{
- 等待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
秘密消息
要求對文件夾下的所有圖片重命名,顯示隱藏的信息。
解決思路:
- 得到文件夾下所有的文件名
- 對每個文件重命名
主要學習文件操作。
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. 冒犯語檢測器
檢測一段文本中是否含有冒犯語。
解決思路:
- 從文檔中讀取文本
- 檢查這段文本是否有冒犯語
本來以為檢測冒犯語的步驟會使用字符串查找匹配的方式,課程簡化為丟給網頁處理。主要還是文件的處理和標準庫中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" >
<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">

</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">

<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()