A. python必背入門代碼是什麼
python必背入門代碼:
defnot_empty(s):
returnsandlen(s。strip())>0
#returnsands。strip()
#如果直接單寫s。strip()那麼s如果是None,會報錯,因為None沒有strip方法。
#如果s是None,那麼Noneand任何值都是False,直接返回false
#如果s非None,那麼判定s。trip()是否為空。
這樣子filter能過濾到None,"",""這樣的值。
分成兩部分看。第一部分是對長度進行序列。相當於就是range(5)他的結果就是。01234。第二部分就是具體的排序規則。排序規則是用nums的值進行排序,reverse沒申明就是默認升序。就是用nums(0到4)的值進行排序,根據這個結果返回的一個range(5)的數組。
根據PEP的規定,必須使用4個空格來表示每級縮進。使用Tab字元和其它數目的空格雖然都可以編譯通過,但不符合編碼規范。支持Tab字元和其它數目的空格僅僅是為兼容很舊的的Python程序和某些有問題的編輯程序。
Python的函數支持遞歸、默認參數值、可變參數,但不支持函數重載。為了增強代碼的可讀性,可以在函數後書寫「文檔字元串」(Documentation Strings,或者簡稱docstrings),用於解釋函數的作用、參數的類型與意義、返回值類型與取值范圍等。可以使用內置函數help()列印出函數的使用幫助。
B. python代碼
你直接寫的true,這個if分支永遠都執行為真的部分。
C. python簡單好玩的代碼
基礎很簡單,也很容易入手,但是任何一門語言都是越深入越難。
D. 求簡潔優美的python代碼例子、片段、參考資料
樓主貼的那段代碼好像是我寫的那段吧,我來告訴你如何寫出來的吧
首先我不是高手,我也沒有人教,我的編程都是自學的,我只是一個業余愛好者.
寫出這樣的代碼很簡單,就是要多練,我只是把python的基本語法學會,然後就不停地練習,我沒有看過樓上的那些資料,我只是不停地碼代碼,或許有捷徑,但是我沒有發現.
我從07年開始寫python的腳本,我一開始的代碼風格也很差,特別是我先學c++,然後再轉python的,當寫的代碼越來越多,對python的了解就會加深,代碼風格也會自動改變的,不需要著急,其實這就是對一門語言的了解程度,你可以看看我回答的問題,我的回答就是我對python的理解,如果你能堅持下來,相信7年後你寫的代碼會比我寫得更好.
樓上的題目有點意思,我也寫一下,不知道對否
s='''
TheZenofPython,byTimPeters
Beautifulisbetterthanugly.
Explicitisbetterthanimplicit.
Simpleisbetterthancomplex.
.
Flatisbetterthannested.
Sparseisbetterthandense.
Readabilitycounts.
Specialcasesaren'tspecialenoughtobreaktherules.
.
Errorsshouldneverpasssilently.
Unlessexplicitlysilenced.
Inthefaceofambiguity,refusethetemptationtoguess.
Thereshouldbeone--andpreferablyonlyone--obviouswaytodoit.
'reDutch.
Nowisbetterthannever.
*right*now.
,it'sabadidea.
,itmaybeagoodidea.
--let'sdomoreofthose!
'''
importre,collections
tail_map={"'s":'is',"'re":'are',"n't":'not'}
data=collections.Counter(re.findall('w+',re.sub("('s|'re|n't)",lambdamatchobj:tail_map[matchobj.group()],s.lower())))
max_len=max(data.values())
print('Totalwordcount:%d',sum(data.values()))
forwordinsorted(data):
print('%*s=>%d'%(max_len,word,data[word]))
E. 怎樣用python獲取電影
實驗室這段時間要採集電影的信息,給出了一個很大的數據集,數據集包含了4000多個電影名,需要我寫一個爬蟲來爬取電影名對應的電影信息。
其實在實際運作中,根本就不需要爬蟲,只需要一點簡單的Python基礎就可以了。
前置需求:
Python3語法基礎
HTTP網路基礎
===================================
第一步,確定API的提供方。IMDb是最大的電影資料庫,與其相對的,有一個OMDb的網站提供了API供使用。這家網站的API非常友好,易於使用。
第二步,確定網址的格式。
第三步,了解基本的Requests庫的使用方法。
F. 求python指令大全
python指令,我覺得你是不是看過一些tw的書籍或介紹啊,簡體中文中基本不這么說。
推薦你看一下python cookbook之類的書做為工具書隨時翻閱。
如果你是剛入門,可以學習《python 核心編程》第二版,有電子版的。
G. Python抓取豆瓣電影排行榜
1.觀察url
首先觀察一下網址的結構 http://movie.douban.com/top250?start=0&filter=&type= :
可以看到,問號?後有三個參數 start、filter、type,其中start代表頁碼,每頁展示25部電影,0代表第一頁,以此類推25代表第二頁,50代表第三頁...
filter顧名思義,是過濾已經看過的電影,filter和type在這里不重要,可以不管。
2.查看網頁源代碼
打開上面的網址,查看源代碼,可以看到信息的展示結構如下:
1 <ol class="grid_view"> 2 <li> 3 <div class="item"> 4 <div class="pic"> 5 <em class="">1</em> 6 <a href="http://movie.douban.com/subject/1292052/"> 7 <img alt="肖申克的救贖" src="http://img3.douban.com/view/movie_poster_cover/ipst/public/p480747492.jpg" class=""> 8 </a> 9 </div>10 <div class="info">11 <div class="hd">12 <a href="http://movie.douban.com/subject/1292052/" class="">13 <span class="title">肖申克的救贖</span>14 <span class="title"> / The Shawshank Redemption</span>15 <span class="other"> / 月黑高飛(港) / 刺激1995(台)</span>16 </a>17 18 19 <span class="playable">[可播放]</span>20 </div>21 <div class="bd">22 <p class="">23 導演: 弗蘭克·德拉邦特 Frank Darabont 主演: 蒂姆·羅賓斯 Tim Robbins /...<br>24 1994 / 美國 / 犯罪 劇情25 </p>26 27 28 <div class="star">29 <span class="rating5-t"><em>9.6</em></span>30 <span>646374人評價</span>31 </div>32 33 <p class="quote">34 <span class="inq">希望讓人自由。</span>35 </p>36 </div>37 </div>38 </div>39 </li>
其中<em class="">1</em>代表排名,<span class="title">肖申克的救贖</span>代表電影名,其他信息的含義也很容易能看出來。
於是接下來可以寫正則表達式:
1 pattern = re.compile(u'<div.*?class="item">.*?<div.*?class="pic">.*?' 2 + u'<em.*?class="">(.*?)</em>.*?' 3 + u'<div.*?class="info">.*?<span.*?class="title">(.*?)' 4 + u'</span>.*?<span.*?class="title">(.*?)</span>.*?' 5 + u'<span.*?class="other">(.*?)</span>.*?</a>.*?' 6 + u'<div.*?class="bd">.*?<p.*?class="">.*?' 7 + u'導演: (.*?) ' 8 + u'主演: (.*?)<br>' 9 + u'(.*?) / (.*?) / '10 + u'(.*?)</p>'11 + u'.*?<div.*?class="star">.*?<em>(.*?)</em>'12 + u'.*?<span>(.*?)人評價</span>.*?<p.*?class="quote">.*?'13 + u'<span.*?class="inq">(.*?)</span>.*?</p>', re.S)
在此處flag參數re.S代表多行匹配。
3.使用面向對象的設計模式編碼
代碼如下:
1 # -*- coding:utf-8 -*- 2 __author__ = 'Jz' 3 import urllib2 4 import re 5 import sys 6 7 class MovieTop250: 8 def __init__(self): 9 #設置默認編碼格式為utf-810 reload(sys)11 sys.setdefaultencoding('utf-8')12 self.start = 013 self.param = '&filter=&type='14 self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64)'}15 self.movieList = []16 self.filePath = 'D:/coding_file/python_file/File/DoubanTop250.txt'17 18 def getPage(self):19 try:20 URL = 'http://movie.douban.com/top250?start=' + str(self.start)21 request = urllib2.Request(url = URL, headers = self.headers)22 response = urllib2.urlopen(request)23 page = response.read().decode('utf-8')24 pageNum = (self.start + 25)/2525 print '正在抓取第' + str(pageNum) + '頁數據...' 26 self.start += 2527 return page28 except urllib2.URLError, e:29 if hasattr(e, 'reason'):30 print '抓取失敗,具體原因:', e.reason31 32 def getMovie(self):33 pattern = re.compile(u'<div.*?class="item">.*?<div.*?class="pic">.*?'34 + u'<em.*?class="">(.*?)</em>.*?'35 + u'<div.*?class="info">.*?<span.*?class="title">(.*?)'36 + u'</span>.*?<span.*?class="title">(.*?)</span>.*?'37 + u'<span.*?class="other">(.*?)</span>.*?</a>.*?'38 + u'<div.*?class="bd">.*?<p.*?class="">.*?'39 + u'導演: (.*?) '40 + u'主演: (.*?)<br>'41 + u'(.*?) / (.*?) / '42 + u'(.*?)</p>'43 + u'.*?<div.*?class="star">.*?<em>(.*?)</em>'44 + u'.*?<span>(.*?)人評價</span>.*?<p.*?class="quote">.*?'45 + u'<span.*?class="inq">(.*?)</span>.*?</p>', re.S)46 while self.start <= 225:47 page = self.getPage()48 movies = re.findall(pattern, page)49 for movie in movies:50 self.movieList.append([movie[0], movie[1], movie[2].lstrip(' / '),
51 movie[3].lstrip(' / '), movie[4],
52 movie[5], movie[6].lstrip(), movie[7], movie[8].rstrip(),53 movie[9], movie[10], movie[11]])54 55 def writeTxt(self):56 fileTop250 = open(self.filePath, 'w')57 try:58 for movie in self.movieList:59 fileTop250.write('電影排名:' + movie[0] + '\r\n')60 fileTop250.write('電影名稱:' + movie[1] + '\r\n')61 fileTop250.write('外文名稱:' + movie[2] + '\r\n')62 fileTop250.write('電影別名:' + movie[3] + '\r\n')63 fileTop250.write('導演姓名:' + movie[4] + '\r\n')64 fileTop250.write('參與主演:' + movie[5] + '\r\n')65 fileTop250.write('上映年份:' + movie[6] + '\r\n')66 fileTop250.write('製作國家/地區:' + movie[7] + '\r\n')67 fileTop250.write('電影類別:' + movie[8] + '\r\n')68 fileTop250.write('電影評分:' + movie[9] + '\r\n')69 fileTop250.write('參評人數:' + movie[10] + '\r\n')70 fileTop250.write('簡短影評:' + movie[11] + '\r\n\r\n')71 print '文件寫入成功...'72 finally:73 fileTop250.close()74 75 def main(self):76 print '正在從豆瓣電影Top250抓取數據...'77 self.getMovie()78 self.writeTxt()79 print '抓取完畢...'80 81 DouBanSpider = MovieTop250()82 DouBanSpider.main()
代碼比較簡單,最後將信息寫入一個文件,沒有什麼需要解釋的地方。
H. python編程 一段文字中搜索電影名字(變3和變形金剛3是同一部)並且按出現次數排序
你是用哪個版本的python?? 不然代碼不同啊...
2.7代碼如下:
#coding:utf-8
import re
datadic={}
string=u'變形金剛3 變形3 變3 我看過變形金剛3 變形3 我看過變3 變形金剛3 變形3變3變形金剛3 變形3變3變形金剛3 變形3變3 哈7 我看過哈利波特7。。。。。。。'
com=re.compile(u'變.{,3}?3')
com1=re.compile(u'哈.{,3}?7')
datadic['%06d'%len(com.findall(string))]=u'變形金剛3'
datadic['%06d'%len((com1.findall(string)))]=u'哈利波特7'
datasort=list(reversed(sorted(datadic)))
k=0
for i in range(len(datasort)):
k+=1
print(u'第%d名是:%s'%(k,datadic[datasort[i]]))
I. python爬蟲抓取電影top20排名怎麼寫
初步接觸python爬蟲(其實python也是才起步),發現一段代碼研究了一下,覺得還比較有用處,Mark下。
上代碼:
#!/usr/bin/python#coding=utf-8#Author: Andrew_liu#mender:cy"""
一個簡單的Python爬蟲, 用於抓取豆瓣電影Top前100的電影的名稱
Anthor: Andrew_liu
mender:cy
Version: 0.0.2
Date: 2017-03-02
Language: Python2.7.12
Editor: JetBrains PyCharm 4.5.4
"""import stringimport reimport urllib2import timeclass DouBanSpider(object) :
"""類的簡要說明
主要用於抓取豆瓣Top100的電影名稱
Attributes:
page: 用於表示當前所處的抓取頁面
cur_url: 用於表示當前爭取抓取頁面的url
datas: 存儲處理好的抓取到的電影名稱
_top_num: 用於記錄當前的top號碼
"""
def __init__(self):
self.page = 1
self.cur_url = "h0?start={page}&filter=&type="
self.datas = []
self._top_num = 1
print u"豆瓣電影爬蟲准備就緒, 准備爬取數據..."
def get_page(self, cur_page):
"""
根據當前頁碼爬取網頁HTML
Args:
cur_page: 表示當前所抓取的網站頁碼
Returns:
返回抓取到整個頁面的HTML(unicode編碼)
Raises:
URLError:url引發的異常
"""
url = self.cur_url try:
my_page = urllib2.urlopen(url.format(page=(cur_page - 1) * 25)).read().decode("utf-8") except urllib2.URLError, e: if hasattr(e, "code"): print "The server couldn't fulfill the request."
print "Error code: %s" % e.code elif hasattr(e, "reason"): print "We failed to reach a server. Please check your url and read the Reason"
print "Reason: %s" % e.reason return my_page def find_title(self, my_page):
"""
通過返回的整個網頁HTML, 正則匹配前100的電影名稱
Args:
my_page: 傳入頁面的HTML文本用於正則匹配
"""
temp_data = []
movie_items = re.findall(r'<span.*?class="title">(.*?)</span>', my_page, re.S) for index, item in enumerate(movie_items): if item.find(" ") == -1:
temp_data.append("Top" + str(self._top_num) + " " + item)
self._top_num += 1
self.datas.extend(temp_data) def start_spider(self):
"""
爬蟲入口, 並控制爬蟲抓取頁面的范圍
"""
while self.page <= 4:
my_page = self.get_page(self.page)
self.find_title(my_page)
self.page += 1def main():
print u"""
###############################
一個簡單的豆瓣電影前100爬蟲
Author: Andrew_liu
mender: cy
Version: 0.0.2
Date: 2017-03-02
###############################
"""
my_spider = DouBanSpider()
my_spider.start_spider()
fobj = open('/data/moxiaokai/HelloWorld/cyTest/blogcode/top_move.txt', 'w+') for item in my_spider.datas: print item
fobj.write(item.encode("utf-8")+'
')
time.sleep(0.1) print u"豆瓣爬蟲爬取完成"if __name__ == '__main__':
main()
運行結果:
J. python抓視頻的代碼急用
推薦你可以採用you-get模塊