Python是什麼
Python是著名的“龜叔”Guido van Rossum在1989年聖誕節期間,爲了打發無聊的聖誕節而編寫的一個編程語言。
創始人Guido van Rossum是BBC出品英劇Monty Python’s Flying Circus(中文:蒙提·派森的飛行馬戲團)的狂熱粉絲,因而將自己創造的這門編程語言命名爲Python。
Python英式發音:/ˈpaɪθən/ ,中文類似‘拍森’。而美式發音:/ˈpaɪθɑːn/,中文類似‘拍賞’。我看麻省理工授課教授讀的是‘拍賞’,我覺得國內大多是讀‘拍森’吧。
2017年python排第一也無可爭議,比較AI第一語言,在當下人工智能大數據大火的情況下,python無愧第一語言的稱號,至於C、C++、java都是萬年的老大哥了,在代碼量比較方面,小編相信java肯定是完爆其它語言的。
不過從這一年的編程語言流行趨勢看,java依然是傳播最多的,比較無論app、web、雲計算都離不開,而其相對python而言,學習路徑更困難一點,想要轉行編程,而且追趕潮流,python已然是最佳語言。
許多大型網站就是用Python開發的,國內:豆瓣、搜狐、金山、騰訊、盛大、網易、百度、阿里、淘寶、熱酷、土豆、新浪、果殼…; 國外:谷歌、NASA、YouTube、Facebook、工業光魔、紅帽…
Python將被納入高考內容
浙江省信息技術課程改革方案已經出臺,Python確定進入浙江省信息技術高考,從2018年起浙江省信息技術教材編程語言將會從vb更換爲Python。其實不止浙江,教育大省北京和山東也確定要把Python編程基礎納入信息技術課程和高考的內容體系,Python語言課程化也將成爲孩子學習的一種趨勢。尤其山東省最新出版的小學信息技術六年級教材也加入了Python內容,小學生都開始接觸Python語言了!!
再不學習,又要被小學生完爆了。。。
掃描下方二維碼關注昌昌,獲得與昌昌直接交流機會~
Python入門教程
- Python教程 - 廖雪峯的官方網站
- Python官網
- Python 100例 | 菜鳥教程
- Python中文社區
- 微信公衆號:Python中文社區
- 微信跳一跳的python外掛項目:https://github.com/wangshub/wechat_jump_game
- 對於有語言基礎的童鞋來說,學習python是很easy的事,而且很funny
Python能做什麼
- 網絡爬蟲
- Web應用開發
- 系統網絡運維
- 科學與數字計算
- 圖形界面開發
- 網絡編程
- 自然語言處理(NLP)
- 人工智能
- 區塊鏈
- 多不勝舉。。。
Python入門爬蟲
這是我的第一個python項目,在這裏與大家分享出來~
- 需求
- 我們目前正在開發一款產品其功能大致是:用戶收到短信如:購買了電影票或者火車票機票之類的事件。然後app讀取短信,解析短信,獲取時間地點,然後後臺自動建立一個備忘錄,在事件開始前1小時提醒用戶。
- 設計
- 開始我們將解析的功能放在了服務端,但是後來考慮到用戶隱私問題。後來將解析功能放到了app端,服務端只負責收集數據,然後將新數據發送給app端。
- 關於服務端主要是分離出兩個功能,一、響應app端請求返回數據。二、爬取數據,存入數據庫。
- 響應請求返回數據使用java來做,而爬取數據存入數據庫使用python來做,這樣分別使用不同語言來做是因爲這兩種語言各有優勢,java效率比python高些,適合做web端,而爬取數據並不是太追求性能且python語言和大量的庫適合做爬蟲。
- 代碼
- 本項目使用python3的版本
- 源碼可在我的碼雲上下載:https://gitee.com/Mrcmc/py-scratch
- 瞭解這個項目你只需要有簡單的python基礎,能瞭解python語法就可以。其實我自己也是python沒學完,然後就開始寫,遇到問題就百度,邊做邊學這樣才不至於很枯燥,因爲python可以做一些很有意思的事情,比如模擬連續登錄掙積分,比如我最近在寫一個預定模範出行車子的python腳本。推薦看廖雪峯的python入門教程
- 首先帶大家看看我的目錄結構,開始我打算是定義一個非常好非常全的規範,後來才發現由於自己不熟悉框架,而是剛入門級別,所以就放棄了。從簡而入:
- 下面咱們按照上圖中的順序,從上往下一個一個文件的講解init.py包的標識文件,python包就是文件夾,當改文件夾下有一個init.py文件後它就成爲一個package,我在這個包中引入一些py供其他py調用。
init.py
# -*- coding: UTF-8 -*-
# import need manager module
import MongoUtil
import FileUtil
import conf_dev
import conf_test
import scratch_airport_name
import scratch_flight_number
import scratch_movie_name
import scratch_train_number
import scratch_train_station
import MainUtil
下面兩個是配置文件,第一個是開發環境的(windows),第二個是測試環境的(linux),然後再根據不同系統啓用不同的配置文件
conf_dev.py
# -*- coding: UTF-8 -*-
# the configuration file of develop environment
# path configure
data_root_path = 'E:/APK98_GNBJ_SMARTSERVER/Proj-gionee-data/smart/data'
# mongodb configure
user = "cmc"
pwd = "123456"
server = "localhost"
port = "27017"
db_name = "smartdb"
conf_test.py
# -*- coding: UTF-8 -*-
# the configuration file of test environment
#path configure
data_root_path = '/data/app/smart/data'
#mongodb configure
user = "smart"
pwd = "123456"
server = "10.8.0.30"
port = "27017"
db_name = "smartdb"
下面文件是一個util文件,主要是讀取原文件的內容,還有將新內容寫入原文件。
FileUtil.py
# -*- coding: UTF-8 -*-
import conf_dev
import conf_test
import platform
# configure Multi-confronment
# 判斷當前系統,並引入相對的配置文件
platform_os = platform.system()
config = conf_dev
if (platform_os == 'Linux'):
config = conf_test
# path
data_root_path = config.data_root_path
# load old data
def read(resources_file_path, encode='utf-8'):
file_path = data_root_path + resources_file_path
outputs = []
for line in open(file_path, encoding=encode):
if not line.startswith("//"):
outputs.append(line.strip('\n').split(',')[-1])
return outputs
# append new data to file from scratch
def append(resources_file_path, data, encode='utf-8'):
file_path = data_root_path + resources_file_path
with open(file_path, 'a', encoding=encode) as f:
f.write(data)
f.close
下面這個main方法控制着執行流程,其他的執行方法調用這個main方法
MainUtil.py
# -*- coding: UTF-8 -*-
import sys
from datetime import datetime
import MongoUtil
import FileUtil
# @param resources_file_path 資源文件的path
# @param base_url 爬取的連接
# @param scratch_func 爬取的方法
def main(resources_file_path, base_url, scratch_func):
old_data = FileUtil.read(resources_file_path) #讀取原資源
new_data = scratch_func(base_url, old_data) #爬取新資源
if new_data: #如果新數據不爲空
date_new_data = "//" + datetime.now().strftime('%Y-%m-%d') + "\n" + "\n".join(new_data) + "\n" #在新數據前面加上當前日期
FileUtil.append(resources_file_path, date_new_data) #將新數據追加到文件中
MongoUtil.insert(resources_file_path, date_new_data) #將新數據插入到mongodb數據庫中
else: #如果新數據爲空,則打印日誌
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '----', getattr(scratch_func, '__name__'), ": nothing to update ")
將更新的內容插入mongodb中
MongoUtil.py
# -*- coding: UTF-8 -*-
import platform
from pymongo import MongoClient
from datetime import datetime, timedelta, timezone
import conf_dev
import conf_test
# configure Multi-confronment
platform_os = platform.system()
config = conf_dev
if (platform_os == 'Linux'):
config = conf_test
# mongodb
uri = 'mongodb://' + config.user + ':' + config.pwd + '@' + config.server + ':' + config.port + '/' + config.db_name
# 將數據寫入mongodb
# @author chenmc
# @param uri connect to mongodb
# @path save mongodb field
# @data save mongodb field
# @operation save mongodb field default value 'append'
# @date 2017/12/07 16:30
# 先在mongodb中插入一條自增數據 db.sequence.insert({ "_id" : "version","seq" : 1})
def insert(path, data, operation='append'):
client = MongoClient(uri)
resources = client.smartdb.resources
sequence = client.smartdb.sequence
seq = sequence.find_one({"_id": "version"})["seq"] #獲取自增id
sequence.update_one({"_id": "version"}, {"$inc": {"seq": 1}}) #自增id+1
post_data = {"_class": "com.gionee.smart.domain.entity.Resources", "version": seq, "path": path,
"content": data, "status": "enable", "operation": operation,
"createtime": datetime.now(timezone(timedelta(hours=8)))}
resources.insert(post_data) #插入數據
項目引入的第三方庫,可使用pip install -r requirements.txt下載第三方庫
requirements.txt
# need to install module# need to install module
bs4
pymongo
requests
json
下面真正的執行方法來了,這五個py分別表示爬取五種信息:機場名、航班號、電影名、列車號、列車站。他們的結構都差不多,如下:
第一部分:定義查找的url;
第二部分:獲取並與舊數據比較,返回新數據;
第三部分:main方法,執行寫入新數據到文件和mongodb中;
scratch_airport_name.py:爬取全國機場
# -*- coding: UTF-8 -*-
import requests
import bs4
import json
import MainUtil
resources_file_path = '/resources/airplane/airportNameList.ini'
scratch_url_old = 'https://data.variflight.com/profiles/profilesapi/search'
scratch_url = 'https://data.variflight.com/analytics/codeapi/initialList'
get_city_url = 'https://data.variflight.com/profiles/Airports/%s'
#傳入查找網頁的url和舊數據,然後本方法會比對原數據中是否有新的條目,如果有則不加入,如果沒有則重新加入,最後返回新數據
def scratch_airport_name(scratch_url, old_airports):
new_airports = []
data = requests.get(scratch_url).text
all_airport_json = json.loads(data)['data']
for airport_by_word in all_airport_json.values():
for airport in airport_by_word:
if airport['fn'] not in old_airports:
get_city_uri = get_city_url % airport['id']
data2 = requests.get(get_city_uri).text
soup = bs4.BeautifulSoup(data2, "html.parser")
city = soup.find('span', text="城市").next_sibling.text
new_airports.append(city + ',' + airport['fn'])
return new_airports
#main方法,執行這個py,默認調用main方法,相當於java的main
if __name__ == '__main__':
MainUtil.main(resources_file_path, scratch_url, scratch_airport_name)
scratch_flight_number.py:爬取全國航班號
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import bs4
import MainUtil
resources_file_path = '/resources/airplane/flightNameList.ini'
scratch_url = 'http://www.variflight.com/sitemap.html?AE71649A58c77='
def scratch_flight_number(scratch_url, old_flights):
new_flights = []
data = requests.get(scratch_url).text
soup = bs4.BeautifulSoup(data, "html.parser")
a_flights = soup.find('div', class_='list').find_all('a', recursive=False)
for flight in a_flights:
if flight.text not in old_flights and flight.text != '國內航段列表':
new_flights.append(flight.text)
return new_flights
if __name__ == '__main__':
MainUtil.main(resources_file_path, scratch_url, scratch_flight_number)
scratch_movie_name.py:爬取最近上映的電影
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import requests
import bs4
import json
import MainUtil
# 相對路徑,也是需要將此路徑存入數據庫
resources_file_path = '/resources/movie/cinemaNameList.ini'
scratch_url = 'http://theater.mtime.com/China_Beijing/'
# scratch data with define url
def scratch_latest_movies(scratch_url, old_movies):
data = requests.get(scratch_url).text
soup = bs4.BeautifulSoup(data, "html.parser")
new_movies = []
new_movies_json = json.loads(
soup.find('script', text=re.compile("var hotplaySvList")).text.split("=")[1].replace(";", ""))
coming_movies_data = soup.find_all('li', class_='i_wantmovie')
# 上映的電影
for movie in new_movies_json:
move_name = movie['Title']
if move_name not in old_movies:
new_movies.append(movie['Title'])
# 即將上映的電影
for coming_movie in coming_movies_data:
coming_movie_name = coming_movie.h3.a.text
if coming_movie_name not in old_movies and coming_movie_name not in new_movies:
new_movies.append(coming_movie_name)
return new_movies
if __name__ == '__main__':
MainUtil.main(resources_file_path, scratch_url, scratch_latest_movies)
scratch_train_number.py:爬取全國列車號
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import bs4
import json
import MainUtil
resources_file_path = '/resources/train/trainNameList.ini'
scratch_url = 'http://www.59178.com/checi/'
def scratch_train_number(scratch_url, old_trains):
new_trains = []
resp = requests.get(scratch_url)
data = resp.text.encode(resp.encoding).decode('gb2312')
soup = bs4.BeautifulSoup(data, "html.parser")
a_trains = soup.find('table').find_all('a')
for train in a_trains:
if train.text not in old_trains and train.text:
new_trains.append(train.text)
return new_trains
if __name__ == '__main__':
MainUtil.main(resources_file_path, scratch_url, scratch_train_number)
scratch_train_station.py:爬取全國列車站
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import bs4
import random
import MainUtil
resources_file_path = '/resources/train/trainStationNameList.ini'
scratch_url = 'http://www.smskb.com/train/'
def scratch_train_station(scratch_url, old_stations):
new_stations = []
provinces_eng = (
"Anhui", "Beijing", "Chongqing", "Fujian", "Gansu", "Guangdong", "Guangxi", "Guizhou", "Hainan", "Hebei",
"Heilongjiang", "Henan", "Hubei", "Hunan", "Jiangsu", "Jiangxi", "Jilin", "Liaoning", "Ningxia", "Qinghai",
"Shandong", "Shanghai", "Shanxi", "Shanxisheng", "Sichuan", "Tianjin", "Neimenggu", "Xianggang", "Xinjiang",
"Xizang",
"Yunnan", "Zhejiang")
provinces_chi = (
"安徽", "北京", "重慶", "福建", "甘肅", "廣東", "廣西", "貴州", "海南", "河北",
"黑龍江", "河南", "湖北", "湖南", "江蘇", "江西", "吉林", "遼寧", "寧夏", "青海",
"山東", "上海", "陝西", "山西", "四川", "天津", "內蒙古", "香港", "新疆", "西藏",
"雲南", "浙江")
for i in range(0, provinces_eng.__len__(), 1):
cur_url = scratch_url + provinces_eng[i] + ".htm"
resp = requests.get(cur_url)
data = resp.text.encode(resp.encoding).decode('gbk')
soup = bs4.BeautifulSoup(data, "html.parser")
a_stations = soup.find('left').find('table').find_all('a')
for station in a_stations:
if station.text not in old_stations:
new_stations.append(provinces_chi[i] + ',' + station.text)
return new_stations
if __name__ == '__main__':
MainUtil.main(resources_file_path, scratch_url, scratch_train_station)
將項目放到測試服務器(centos7系統)中運行起來,我寫了一個crontab,定時調用他們,下面貼出crontab。
/etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
0 0 * * * root python3 /data/app/smart/py/scratch_movie_name.py >> /data/logs/smartpy/out.log 2>&1
0 1 * * 1 root python3 /data/app/smart/py/scratch_train_station.py >> /data/logs/smartpy/out.log 2>&1
0 2 * * 2 root python3 /data/app/smart/py/scratch_train_number.py >> /data/logs/smartpy/out.log 2>&1
0 3 * * 4 root python3 /data/app/smart/py/scratch_flight_number.py >> /data/logs/smartpy/out.log 2>&1
0 4 * * 5 root python3 /data/app/smart/py/scratch_airport_name.py >> /data/logs/smartpy/out.log 2>&1
後續
目前項目已經正常運行了三個多月啦。。。
有問題反饋
在閱讀與學習中有任何問題,歡迎反饋給我,可以用以下聯繫方式跟我交流
- 微信公衆號:裸睡的豬
- 在下面留言
- 直接給我私信
關於此公衆號
- 後期或提供各種軟件的免費激活碼
- 推送python,java等編程技術文章和麪試技巧
- 當然你們可以將你們感興趣的東西直接送給我
- 謝謝你們真誠的關注,此公衆號以後獲得的收益將
全部
通過抽獎的形式送給大家 - 以後如果博主要創業的話,也會在此公衆號中挑選小夥伴哦~
- 希望大家分享出去,讓更多想學習python的朋友看到~