麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發(fā)設計 > 正文

Python學習(一)

2019-11-14 10:39:29
字體:
來源:轉載
供稿:網友
#!/usr/bin/env python3# -*- coding: utf-8 -*-#學習自廖雪峰老師的博客及慕課網python課程:#廖雪峰的官方網站:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000#慕課網鏈接:http://www.imooc.com/course/list?c=python    - 字符串和編碼
u'中文'

如果中文字符串在Python環(huán)境下遇到 UnicodeDecodeError,這是因為.py文件保存的格式有問題。可以在第一行添加注釋

# -*- coding: utf-8 -*-
    - 占位符

常見的占位符有:

%s字符串
%d整數(shù)
%f浮點數(shù)
%x十六進制整數(shù)
    - 使用list、tuple、dict和set    - List    ['value']1.list.append()  #list增加屬性2.list.insert(索引數(shù),‘增加的字段’)3.pop()方法總是刪掉list的最后一個元素,并且它還返回這個元素,所以我們執(zhí)行 L.pop() 后,會打印出 'Paul'。。由于Paul的索引是2,因此,用 pop(2)把Paul刪掉4.切片    L[0:3:1]    表示,從索引0開始取,直到索引3為止,中間間隔為0,但不包括索引3。即索引0,1,2,正好是3個元素。——>可以針對str類型截取字符串    - tuple(元組) ('value') 寫死的list    - dict字典     {key:value,}len() 函數(shù)可以計算任意集合的大小更新dict    d['Paul'] = 72迭代dict的key和value            for key, value in d.items():    - set (['value'])
應用場景        weekdays = set(['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']) 更新set        add()
    - 1.切片: L[0:3]表示,從索引0開始取,直到索引3為止,但不包括索引3    - 
>>> d = {'a': 1, 'b': 2, 'c': 3}>>> for key in d:...     PRint(key)
判斷可迭代
>>> from collections import Iterable>>> isinstance('abc', Iterable) # str是否可迭代True>>> isinstance([1,2,3], Iterable) # list是否可迭代True>>> isinstance(123, Iterable) # 整數(shù)是否可迭代False
    - 3.列表生成式
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

寫列表生成式時,把要生成的元素x * x放到前面,后面跟for循環(huán),就可以把list創(chuàng)建出來,十分有用,多寫幾次,很快就可以熟悉這種語法。

for循環(huán)后面還可以加上if判斷,這樣我們就可以篩選出僅偶數(shù)的平方:

>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100]       - 函數(shù)filter()函數(shù)filter()根據(jù)判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。sorted()函數(shù)可對list進行排序len()統(tǒng)計字符list.append('')追加元素到末尾list.pop(i)刪除i索引位置的元素range()函數(shù)  range(5)生成的序列是從0開始小于5list()函數(shù)可以轉換為listadd(key)方法可以添加元素到set中remove(key)方法可以刪除元素isinstance()可以判斷一個變量的類型    - get & set@property---這是關鍵字,固定格式,能讓方法當“屬性”用。@score.setter---前面的"score"是@property緊跟的下面定義的那個方法的名字,"setter"是關鍵字,這種“@+方法名字+點+setter”是個固定格式與@property搭配使用。    - 模塊
1.datetime   Python處理日期和時間的標準庫。  如果僅導入import datetime,則必須引用全名datetime.datetime
now = datetime.now() # 獲取當前datetime
dt = datetime(2015, 4, 19, 12, 20) # 用指定日期時間創(chuàng)建datetime
dt.timestamp() # 把datetime轉換為timestamp把str轉換為datetime。轉換方法是通過datetime.strptime()實現(xiàn)
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)2.collectionsnamedtupledequedefaultdictOrderedDictCounter

3.hashlib

摘要算法md5計算出一個字符串的MD5值:

import hashlib
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
print(md5.hexdigest())
4.itertools    - 面向對象

舉個例子,Python的網絡服務器有TCPServer、UDPServer、UnixStreamServer、UnixDatagramServer,而服務器運行模式有 多進程ForkingMixin 和 多線程ThreadingMixin兩種。

要創(chuàng)建多進程模式的 TCPServer:

class MyTCPServer(TCPServer, ForkingMixin)    pass

要創(chuàng)建多線程模式的 UDPServer:

class MyUDPServer(UDPServer, ThreadingMixin):    pass

如果沒有多重繼承,要實現(xiàn)上述所有可能的組合需要 4x2=8 個子類。

    - 裝飾器@property,可以將python定義的函數(shù)“當做”屬性訪問,從而提供更加友好訪問方式    - 錯誤、調試和測試

斷言

凡是用print()來輔助查看的地方,都可以用斷言(assert)來替代:

try:    print('try...')    r = 10 / 0    print('result:', r)except     ZeroDivisionError as e:    print('except:', e)finally:    print('finally...')print('END')

1.
IndexError: list index out of range索引越界2.
File "index.py", line 11, in <module>    print d['Paul']KeyError: 'Paul'字典key不存在解決:dict本身提供的一個 get 方法,在Key不存在的時候,返回Nonepy->二級制文件(對語法進行檢查)->try-except e ,continue隨機數(shù)import randomnumber= random.randint(0, 100)
    - IO編程

但是每次都這么寫實在太繁瑣,所以,Python引入了with語句來自動幫我們調用close()方法:

with open('/path/to/file', 'r') as f:    print(f.read())    - 進程和線程【協(xié)程】    - 正則表達式

在正則表達式中,如果直接給出字符,就是精確匹配。用/d可以匹配一個數(shù)字,/w可以匹配一個字母或數(shù)字,所以:

'00/d'可以匹配'007',但無法匹配'00A'

'/d/d/d'可以匹配'010'

'/w/w/d'可以匹配'py3'

.可以匹配任意字符,所以:

'py.'可以匹配'pyc''pyo''py!'等等。

要匹配變長的字符,在正則表達式中,用*表示任意個字符(包括0個),用+表示至少一個字符,用?表示0個或1個字符,用{n}表示n個字符,用{n,m}表示n-m個字符:

來看一個復雜的例子:/d{3}/s+/d{3,8}

我們來從左到右解讀一下:

/d{3}表示匹配3個數(shù)字,例如'010'

/s可以匹配一個空格(也包括Tab等空白符),所以/s+表示至少有一個空格,例如匹配' '' '等;

/d{3,8}表示3-8個數(shù)字,例如'1234567'

因此我們強烈建議使用Python的r前綴,就不用考慮轉義的問題了:

s = r'ABC/-001'# Python的字符串# 對應的正則表達式字符串不變:# 'ABC/-001'

先看看如何判斷正則表達式是否匹配:

>>> import re>>> re.match(r'^/d{3}/-/d{3,8}$', '010-12345')<_sre.SRE_Match object; span=(0, 9), match='010-12345'>>>> re.match(r'^/d{3}/-/d{3,8}$', '010 12345')>>>

match()方法判斷是否匹配,如果匹配成功,返回一個Match對象,否則返回None。常見的判斷方法就是:

test = '用戶輸入的字符串'if re.match(r'正則表達式', test):    print('ok')else:    print('failed')    - 圖形界面    - Json
    - 網絡編程    - 訪問數(shù)據(jù)庫    - MySQL    - 框架    - BeautifulSoupBeautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼
解析器使用方法優(yōu)勢劣勢
Python標準庫BeautifulSoup(markup, “html.parser”)Python的內置標準庫執(zhí)行速度適中文檔容錯能力強Python 2.7.3 or 3.2.2)前 的版本中文檔容錯能力差
lxml HTML 解析器BeautifulSoup(markup, “l(fā)xml”)速度快文檔容錯能力強需要安裝C語言庫
lxml XML 解析器BeautifulSoup(markup, [“l(fā)xml”, “xml”])BeautifulSoup(markup, “xml”)速度快唯一支持XML的解析器需要安裝C語言庫
html5libBeautifulSoup(markup, “html5lib”)最好的容錯性以瀏覽器的方式解析文檔生成HTML5格式的文檔速度慢不依賴外部擴展
 soup=BeautifulSoup(html)  #創(chuàng)建 beautifulsoup 對象

四大對象種類

Tag(通俗點講就是 HTML 中的一個個標簽)NavigableStringBeautifulSoupComment1.tag:
12print soup.title#<title>The Dormouse's story</title>
2.NavigableString獲取標簽內部的文字怎么辦呢?很簡單,用 .string 即可
12print soup.p.string#The Dormouse's story

遍歷文檔樹

.contents

tag 的 .content 屬性可以將tag的子節(jié)點以列表的方式輸出,我們可以用列表索引來獲取它的某一個元素

12print soup.head.contents[0]#<title>The Dormouse's story</title>
.children
12forchildin  soup.body.children:    print child
12345<pclass="title"name="dromouse"><b>The Dormouse'sstory</b></p> <pclass="story">Once uponatime there were three little sisters;andtheir names were<aclass="sister"href="http://example.com/elsie"id="link1"><!--Elsie--></a>,<aclass="sister"href="http://example.com/lacie"id="link2">Lacie</a>and
.strings如果一個標簽里面沒有標簽了,那么 .string 就會返回標簽里面的內容。如果標簽里面只有唯一的一個標簽了,那么 .string 也會返回最里面的內容,如果tag包含了多個子節(jié)點,tag就無法確定,string 方法應該調用哪個子節(jié)點的內容, .string 的輸出結果是 None.stripped_strings 輸出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白內容
123456789101112forstringinsoup.stripped_strings:    print(repr(string))    # u"The Dormouse's story"    # u"The Dormouse's story"    # u'Once upon a time there were three little sisters; and their names were'    # u'Elsie'    # u','    # u'Lacie'    # u'and'    # u'Tillie'    # u';/nand they lived at the bottom of a well.'    # u'...'
.parent (有點像pwd)
123p=soup.pprintp.parent.name#body

搜索文檔樹

方法一:

find_all( name , attrs , recursive , text , **kwargs )

name 參數(shù)可以查找所有名字為 name 的tag

下面方法校驗了當前元素,如果包含 class 屬性卻不包含 id 屬性,那么將返回 True:

12def has_class_but_no_id(tag):    returntag.has_attr('class')andnottag.has_attr('id')

將這個方法作為參數(shù)傳入 find_all() 方法,將得到所有<p>標簽:

1234soup.find_all(has_class_but_no_id)# [<p class="title"><b>The Dormouse's story</b></p>,#  <p class="story">Once upon a time there were...</p>,#  <p class="story">...</p>]
keyWord 參數(shù)
12soup.find_all(id='link2')# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

如果傳入 href 參數(shù),Beautiful Soup會搜索每個tag的”href”屬性

12soup.find_all(href=re.compile("elsie"))# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

使用多個指定名字的參數(shù)可以同時過濾tag的多個屬性

12soup.find_all(href=re.compile("elsie"),id='link1')# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

在這里我們想用 class 過濾,不過 class 是 python 的關鍵詞,這怎么辦?加個下劃線就可以

1234soup.find_all("a",class_="sister")# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

有些tag屬性在搜索不能使用,比如HTML5中的 data-* 屬性

123data_soup=BeautifulSoup('<div data-foo="value">foo!</div>')data_soup.find_all(data-foo="value")# SyntaxError: keyword can't be an expression

但是可以通過 find_all() 方法的 attrs 參數(shù)定義一個字典參數(shù)來搜索包含特殊屬性的tag

12data_soup.find_all(attrs={"data-foo":"value"})# [<div data-foo="value">foo!</div>]
limit 參數(shù)
123soup.find_all("a",limit=2)# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

(2)find( name , attrs , recursive , text , **kwargs )

它與 find_all() 方法唯一的區(qū)別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果

方法二:

CSS選擇器

soup.select(),返回類型是 listsoup=BeautifulSoup(html,'lxml')print type(soup.select('title'))print soup.select('title')[0].get_text() fortitle insoup.select('title'):    print title.get_text()以上的 select 方法返回的結果都是列表形式,可以遍歷形式輸出,然后用 get_text() 方法來獲取它的內容。    - 其他if-elif-else迭代:enumerate() 函數(shù):自動把每個元素變成 (index, element) 這樣的tuple,再迭代,就同時獲得了索引和元素本身。
[x * x for x in range(1, 11) if x % 2 == 0]

傳入**kw 即可傳入任意數(shù)量的參數(shù),并通過 setattr() 綁定屬性,iteritems()用于字典kw的遍歷

參考代碼:

class Person(object):    def __init__(self, name, gender, **kw):        self.name = name        self.gender = gender        for k, v in kw.iteritems():            setattr(self, k, v)p = Person('Bob', 'Male', age=18, course='Python')print p.ageprint p.course

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 亚洲成人免费视频在线 | gogo全球大胆高清人露出91 | 亚洲电影免费观看国语版 | 蜜桃欧美性大片免费视频 | 色综合久久久久久 | 国产精品成人一区二区三区电影毛片 | 在线成人免费观看www | 黄网站进入 | 久久精品综合视频 | 久综合 | 欧美高清视频一区 | 蜜桃网站在线观看 | 亚洲综人网| 国产精品av久久久久久网址 | 国产亚洲精品久久久久久久软件 | 成人小视频免费在线观看 | 国产精品久久久久久一区二区三区 | 天天曰夜夜操 | 性视频久久 | 久久艹精品视频 | 日韩精品久久久久久 | 国产成人综合在线观看 | 免费看操片 | 羞羞电影网 | 92看片淫黄大片欧美看国产片 | 中午字幕无线码一区2020 | 午夜视频在线免费观看 | 久久久一区二区三区精品 | 国产日韩免费观看 | 双性帝王调教跪撅打屁股 | 双性精h调教灌尿打屁股的文案 | 久久久久久久久久一本门道91 | 成人免费毛片片v | 91看片在线播放 | 国产精品欧美久久久久一区二区 | 美女黄视频在线观看 | www.9191.com| 国产精品7区 | 懂色粉嫩av久婷啪 | www.成人免费 | av在线1 |