Python Basic 2

练完基础以后,还需要看看一些基本的概念就开始按照官方文档来做一些简单的demo,但是我得提前说一下一些基本的东西。

比如说我会在每张新建的页面的头部会加上

#!/usr/bin/env python
# -*- coding: utf-8 -*-  

跟着文档做完以后还是觉得缺点什么,因为还是对一些概念性的东西不明白,后来又去Udacity看了一下印度阿三讲的,稍稍明白一点,可能还是自己的理解不够透彻吧。

先说一下做demo的感想吧,每个人对文档的内容理解都是不一样的,也就是说一篇再详细的操作文档,你按照它所说一步一步走下去,最理想的情况是你得到和它所说的结果一致。但是生活并不能像韩剧那样发展,很有可能在过程中碰到这样或者是那样的bug,不要灰心,不要心急,作者也不想这样的,现实是他没有考虑到你用的是什么系统,开发环境,就算这些都是一样,他也不能保证你不会把a敲成b。

让我们来做一个非常酷的小demo,建3个Python文件,media.py entertainment.py fresh_tomatoes.py在同一级目录下:

media.py

1
2
3
4
5
6
7
8
9
10
11
12
import webbrowser

class Movie():

def __init__(self, title, storyline, douban_image, video_url):
self.title = title
self.storyline = storyline
self.douban_image = douban_image
self.video_url = video_url

def show_movie(self):
webbrowser.open(self.video_url)

entertainment.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import fresh_tomatoes
import media


shaonv = media.Movie("Our Times",
"“路人少女”林真心暗恋校草,“校霸”徐太宇明爱校花,因此两人组成史上最强失恋联盟,用尽各种拆散大法,终得逞,但这真的是happy ending吗?",
"http://img31.mtime.cn/mg/2015/11/17/140258.10433511_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")

fallinlove = media.Movie("Mojin-The Lost Legend",
"上世纪90代初,探墓高手胡八一决定金盆洗手。他与未婚妻Shirley杨移居美国,婚礼前,发现20年前死在“百眼窟”的初恋对象丁思甜居然还活着。老胡联手Shirley杨和老搭档,发现流传千年的惊天秘密。",
"http://img31.mtime.cn/mg/2015/12/16/105727.28403894_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")


laopaoer = media.Movie("Mr. Six",
"曾经风光四九城的老炮六爷,难以适应社会巨变,蛰伏于胡同深处,过着溜鸟、管闲事、发牢骚的无聊日子。 某日,六爷得知,离家出走已久的儿子晓波,因与人纠纷,被新崛起的一代以小飞为首年轻顽主非法拘禁。为了解救儿子,..",
"http://img31.mtime.cn/mg/2015/12/09/094723.69065942_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")

ergun = media.Movie("Devil and Angel",
"改编自同名话剧,讲述了莫非里和查小刀两个性格迥异的人狭路相逢发生的故事。",
"http://img31.mtime.cn/mg/2015/11/04/094019.43784759_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")

menshen = media.Movie("Little Door Gods",
"故事发生在神界和人间的江南小镇。门神神荼和郁垒是两兄弟,因为近些年人间对神仙们的冷落,神界经济萧条,门神、土地爷这些小神们面临下岗失业的危险。于是,二门神郁垒决定去人间,做一番惊天动地的事情,证明门神的价值。门神俩兄弟..",
"http://img31.mtime.cn/mg/2015/12/16/100905.69509860_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")

zuiaide = media.Movie("The Secret",
"该片讲述了黎明饰演的凯峰与王珞丹饰演的秋捷是一对恩爱夫妻,在一次雪山攀登中发生意外,凯峰无法走出痛失爱人的阴影整日沉浸在不可自拔的思念中,也是在这种强烈爱意下,秋捷重回到了他的身边。",
"http://img31.mtime.cn/mg/2015/12/11/092153.84483993_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")

xiagao = media.Movie("极限挑战",
"黄渤、孙红雷、黄磊、罗志祥、王迅、张艺兴在拍《极限挑战》时,意外被雷“劈”回到几百年前的大明朝。6人得到皇帝恩宠,却因为一个失误造成皇帝驾崩。",
"http://img31.mtime.cn/mg/2015/12/01/095119.94576288_270X405X4.jpg",
"https://www.youtube.com/watch?v=uBKZKv_42Ho&list=PLAwxTw4SYaPnYajEbZvqtcVWQ6XGhvtOW&index=115")

movie = [shaonv, fallinlove, laopaoer, ergun, menshen, zuiaide, xiagao]
fresh_tomatoes.open_movies_page(movie)

fresh_tomatoes.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import webbrowser
import os
import re


# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html, charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<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">
<img src="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="#">It should be more cool to do this</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">
<img src="{douban_image}" width="220" height="342">
<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.video_url)
youtube_id_match = youtube_id_match or re.search(
r'(?<=be/)[^&#]+', movie.video_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,
douban_image=movie.douban_image,
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)

对,没错。你把这3个文件copy下来放到你本地跑起来,然后看到fresh_tomatoes.html生成,跑在浏览器里面

接下来我还附上几个自己做的小东西

break_time.py

1
2
3
4
5
6
7
8
9
10
11
12
import time
import webbrowser

total_count = 3
break_count = 0

print ("This program started on "+ time.ctime())

while(break_count < total_count):
time.sleep(5)
webbrowser.open("http://www.baidu.com")
break_count += 1

check_text.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import urllib

def read_text():

quotes = open("/Users/darcy/short-term/test.txt")
contents_of_file = quotes.read()
print (contents_of_file)
quotes.close()
check_word(contents_of_file)

def check_word(check_text):
connection = urllib.urlopen("http://www.wdly.com/profanity?q=" + check_text)
output = connection.read()
print (output)
connection.close()

read_text()

rename_file.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os

def rename_file():

file_list = os.listdir(r"/Users/darcy/short-term/images")
print(file_list)
save_path = os.getcwd()
print ("Current Working Directory is "+ save_path)
os.chdir(r"/Users/darcy/short-term/images")



for name in file_list:
print ("Old Name - "+name)
print ("New Name - "+name.translate(None, "0123456789"))
os.rename(name, name.translate(None, "0123456789"))
os.chdir(save_path)


rename_file()

send_text.py

1
2
3
4
5
6
7
8
9
10
11
12
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC4527c55338f4a89ec56aa4e1b819d6cb"
auth_token = "18d83d4a0e988260c44489319ca32d09"
client = TwilioRestClient(account_sid, auth_token)

message = client.messages.create(
body="Darcy, you are really awesome man in the world",
to="+8613521186285",
from_="+15005550006")
print message.sid

一个简单的爬虫demo

scrape.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from bs4 import BeautifulSoup
import requests
import csv

source = requests.get('http://coreyms.com').text

soup = BeautifulSoup(source, 'lxml')

csv_file = open('cms_scrape.csv', 'w')

csv_writer = csv.writer(csv_file)
csv_writer.writerow(['headline', 'summary', 'video_link'])

for article in soup.find_all('article'):
headline = article.h2.a.text
print(headline)

summary = article.find('div', class_='entry-content').p.text
print(summary)

try:
vid_src = article.find('iframe', class_='youtube-player')['src']

vid_id = vid_src.split('/')[4]
vid_id = vid_id.split('?')[0]

yt_link = f'https://youtube.com/watch?v={vid_id}'
except Exception as e:
yt_link = None

print(yt_link)

print()

csv_writer.writerow([headline, summary, yt_link])

csv_file.close()