進入Python世界——Python基礎知識

本文通過實例練習Python基礎語法, python版本2.7

# -*- coding: utf-8 -*-
import randomimport re
import requests
from bs4 import BeautifulSoup

# 爬取糗事百科的首頁內容
def qiushibaike():content = requests.get('http://www.qiushibaike.com/').contentsoup = BeautifulSoup(content, 'html.parser')# print(soup.get_text())for div in soup.find_all('div', {'class': 'foot'}):print(div.text.split())# for div in soup.find_all('div', {'class': 'content'}):
# 字符串常見處理方法 def demo_string():stra = 'hello world'print(stra.capitalize())print(stra.replace('world', 'victor'))strb = ' \n\rhello world \r\n'print(0, strb)print(1, strb.lstrip())print(2, strb.rstrip(), 'xx')strc = 'hello w'print(3, strc.startswith('hel'))print(4, strc.endswith('w'))print(5, stra + strb + strc)print(6, len(stra), len(strb), len(strc))print(7, '-'.join(['a', 'b', 'c'])) # a-b-cprint(8, strc.split(' '))print(9, strc.find('llo'))
# 運算符操作
def demo_operation():print(1, 1 + 2, 5 / 2, 5 * 2, 5 - 2)print(2, 1 + 2, 5.0 / 2, 5 * 2, 5 - 2)print(3, True, not True, False, not False)print(4, 1 << 2, 88 >> 2)print(5, 1 < 2, 5 > 3)print(6, 5 & 3, 5 ^ 3, 5 | 3)x = 3y = 5.0print(7, x, y, type(x), type(y))
# 函數
def demo_buildinfunction():print(1, max(1, 2), min(5, 3))print(2, len('xxx'), len([3, 4, 5]))print(3, abs(-2), abs(7))print(4, range(1, 10, 2))# print(5, '\n'.join(dir(list)))x = 2print(6, eval('x+3'))print(7, chr(65), ord('a'))print(8, divmod(11, 3))
# 控制流
def demo_controlflow():score = 65;if score > 99:print(1, 'A')elif score > 60 & score <= 99:print(2, 'B')else:print(3, 'C')while score < 100:print(4, score)score += 10if score > 80:breakfor i in range(0, 10):if i == 0:passif i == 3:continueif i < 5:print(5, i*i)if i == 7:break
# 列表 def demo_list():lista = [1, 2, 3]print(1, lista)# print(dir(list))listb = ['a', 1, 1.0, 4, 2]print(2, listb)lista.extend(listb)print(3, lista)print(4, len(lista))print(5, 'a' in lista, 'b' in listb)lista += listbprint(lista)listb.insert(0, 'www')print(listb)listb.pop(1)print(listb)# listb.sort()print(listb)print(6, listb[0], listb[1], listb[2])print(7, [0] * 10)print(8, listb * 2)listb.reverse()print(9, listb)t = (1, 2, 3,1)print(10, t)# print(11, t.count())print(11, t.count(1), len(t))
# 字典
def demo_dict():dicta = {4 : 16, 1 : 1, 2 : 4, 3 : 9, 'a' : 'b'}print(1, dicta)print(2, dicta.keys(), dicta.values())for key, value, in dicta.items():print(key, value)for key in dicta.keys():print(key)# 2.0版本是has_keys()方法print(3, dicta.__contains__(1), dicta.__contains__(11))dictb = {'+': add, '-': sub}print(4, dictb.get('-')(5, 3))print(4, dictb['+'](1, 2))print(5, dictb.__contains__('+'))del dictb['+']print(5, dictb.__contains__('+'))print(5, dictb)dictb.pop('-')print(6, dictb)dictb['x'] = 'y'print(7, dictb)def add(a, b):return a + bdef sub(a, b):return a - b# 集合 def demo_set():lista = [1, 2, 3]lista1 = (1, 2, 3)seta = set(lista)seta1 = set(lista1)print(1, seta)print(1, seta1)setb = set((2, 3, 4))print(2, seta.intersection(setb))print(3, seta & setb)print(4, seta | setb, seta.union(setb))print(5, seta - setb, setb - seta)seta.add('xxx')print(6, seta)print(7, len(seta))print(8, seta.isdisjoint(set((1, 2))))print(9, 1 in seta)
# 類
class User:type = 'USER'def __init__(self, name, uid):self.name = nameself.uid = uiddef __repr__(self):# toStirng()return 'i am ' + self.name + ' ' + str(self.uid) + ' ' + self.type# 繼承 class Guest(User):type = 'GUEST'def __repr__(self):return "I am guest: " + self.name + ' ' + str(self.uid) + ' ' + self.typeclass Admin(User):type = 'ADMIN'def __init__(self, name, uid, group):User.__init__(self,name, uid)self.group = groupdef __repr__(self):return 'I am admin: ' + self.name + ' ' + str(self.uid) + ' ' + self.group + ' ' + self.typedef create_user(type):if type == 'USER':return User('u1', 1)elif type == 'ADMIN':return Admin('a1', 1, 'shu')else:return Guest('g1', 1)
# 異常
def demo_exception():try:print(2/1)# print(2/0)raise Exception('Raise Error', 'xxx')except Exception as e:print('error', e)finally:print('clean up')def demo_obj():user1 = User('victor', 1)print(user1.__repr__())print(user1)guest = Guest('xunuo', 2)print(guest)admin = Admin('Qingde', 2, 'shanghai university')print(admin)print(create_user('ADMIN'))def demo_random():random.seed(11)for i in range(0, 5):print(1, random.randint(0,100))print(2, int(random.random()*100))print(3, random.choice(range(0, 100, 5))) # 抽獎print(4, random.sample(range(0, 100, 10), 4)) # 抽幾個 lista = [1, 2, 3, 4, 5]random.shuffle(lista)print(lista)def demo_regex():str = 'abc123def12gh15'p1 = re.compile('[\d]+')p2 = re.compile('\d')print(1, p1.findall(str))print(2, p2.findall(str))str1 = 'axxx@163.com, bsad@google.com, cdd@qq.com, dasd@qq.com, eda@163.com'p3 = re.compile('[\w]+@[163|qq]+\.com') # 不能有空格print(3, p3.findall(str1))str = '<html><h>title</h><body>content</body></html>'p4 = re.compile('<h>[^<]+</h>')print(4, p4.findall(str))p4 = re.compile('<h>[^<]+</h><body>[^<]+</body>')print(5, p4.findall(str))str = 'xx2017-06-06zzz'p5 = re.compile('\d{4}-\d{2}-\d{2}')print(6, p5.findall(str))if __name__ == '__main__':# print('hello world') qiushibaike()# demo_string()# demo_operation()# demo_buildinfunction()# demo_controlflow()# demo_list()# demo_dict()# demo_set()# demo_obj()# demo_exception()# demo_random()# demo_regex()

?

轉載于:https://www.cnblogs.com/weekend/p/6961126.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/258496.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/258496.shtml
英文地址,請注明出處:http://en.pswp.cn/news/258496.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

db2 版本發布歷史_數據庫各廠商的發展歷史(2. DB2 of IBM)

如若轉載&#xff0c;請務必注明出處&#xff0c;iihero 2008.9.26于CSDN1973年&#xff0c;IBM研究中心啟動System R項目&#xff0c;為DB2的誕生打下良好基礎。System R 是 IBM 研究部門開發的一種產品&#xff0c;這種原型語言促進了技術的發展并最終在1983年將 DB2 帶到了商…

android---簡單的通訊錄

遺留問題:獲取頭像及其他信息 利用adapter和Cursor來獲取聯系人的姓名和手機號,重在復習之前學過的內容加深自己的理解. 其中需要注意的部分: 1.adapter中的getview的優化問題,用到tag這一屬性 2.onBackPressed()返回方法的重寫,使得程序更加人性化 下面是主要代碼 1.adapte…

win phone 獲取并且處理回車鍵事件

參考自&#xff1a;http://www.cnblogs.com/mohe/archive/2013/03/18/2966540.html 實用場景,比如輸入帳號和密碼啦,輸入搜索關鍵字啦.protected override void OnKeyDown(KeyEventArgs e) {if (e.Key Key.Enter){MessageBox.Show("我是windows phone 回車鍵"); …

【2020年】最新中國科學院大學學位論文寫作規范

最近在完成國科大博士論文寫作的時候&#xff0c;有一些心得體會&#xff0c;特此總結下來&#xff0c;以饗讀者&#xff0c;尤其是可愛的學弟學妹們。需要注意的是&#xff0c; 以下僅僅是我自己的心得而已&#xff0c;僅供參考。 1. 首先推薦大家使用國科大的Latex模板&…

談談Java基礎數據類型

Java的基本數據類型 類型意義取值boolean布爾值true或falsebyte8位有符號整型-128~127short16位有符號整型-pow(2,15)~pow(2,15)-1int32位有符號整型-pow(2,31)~pow(2,31)-1long64位有符號整型-pow(2,63)~pow(2,63)-1float32位浮點數IEEE754標準單精度浮點數double64位浮點數IE…

用fft對信號進行頻譜分析實驗報告_示波器上的頻域分析利器,Spectrum View測試分析...

簡介&#xff1a;【Spectrum View技術文章系列】從基礎篇開始&#xff0c;講述利用示波器上的Spectrum View功能觀測多通道信號頻譜分析正文&#xff1a;示波器和頻譜儀都是電子測試測量中必不可少的測試設備&#xff0c;分別用于觀察信號的時域波形和頻譜。時域波形是信號最原…

DataTable RowFilter 過濾數據

用Rowfilter加入過濾條件 eg&#xff1a; string sql "select Name,Age,Sex from UserInfo"; DataTable dt DataAccess.GetDataTable(sql);//外部方法&#xff08;通過一條查詢語句返回一個DataTable&#xff09; dt.DefaultView.RowFilter "Sex女"; dt…

platform_device與platform_driver

做Linux方面也有三個多月了&#xff0c;對代碼中的有些結構一直不是非常明確&#xff0c;比方platform_device與platform_driver一直分不清關系。在網上搜了下&#xff0c;做個總結。兩者的工作順序是先定義platform_device -> 注冊 platform_device->&#xff0c;再定義…

復盤caffe安裝

最近因之前的服務器上的caffe奔潰了&#xff0c;不得已重新安裝這一古老的深度學習框架&#xff0c;之前也嘗試了好幾次&#xff0c;每次都失敗&#xff0c;這次總算是成功了&#xff0c;因此及時地總結一下。 以下安裝的caffe主要是針對之前虹膜分割和鞏膜分割所需的caffe版本…

HP P2000 RAID-5兩塊盤離線的數據恢復報告

1. 故障描述本案例是HP P2000的存儲vmware exsi虛擬化平臺&#xff0c;由RAID-5由10塊lT硬盤組成&#xff0c;其中6號盤是熱備盤&#xff0c;由于故障導致RAID-5磁盤陣列的兩塊盤掉線&#xff0c;表現為兩塊硬盤亮黃燈。 經用戶方維護人員檢測&#xff0c;故障硬盤應為物理故障…

微智魔盒騙局_微智魔盒官宣

原標題&#xff1a;微智魔盒官宣微智魔盒官方宣傳視頻微達國際集團創建于2011年&#xff0c;是一家堅持創新的集科研、產銷、服務為一體的智能化產業平臺&#xff0c;致力于國際領先的專注人工智能領域的產業投資、項目孵化、教育培訓&#xff0c;并提供終極解決方案。集團創新…

瑞柏匡丞_移動互聯的發展現狀與未來

互聯網作為人類文明史上最偉大、最重要的科技發明之一&#xff0c;發展到今天&#xff0c;用翻天覆地來形容并不過分。而作為傳統互聯網的延伸和演進方向&#xff0c;移動互聯網更是在近兩年得到了迅猛的發展。如今&#xff0c;越來越多的用戶得以通過高速的移動網絡和強大的智…

android 進程間通信數據(一)------parcel的起源

關于parcel&#xff0c;我們先來講講它的“父輩” Serialize。 Serialize 是java提供的一套序列化機制。但是為什么要序列化&#xff0c;怎么序列化&#xff0c;序列化是怎么做到的&#xff0c;我們將在本文探討下。 一&#xff1a;java 中的serialize 關于Serialize這個東東&a…

為什么torch.nn.Linear的表達形式為y=xA^T+b而不是常見的y=Ax+b?

今天看代碼&#xff0c;對比了常見的公式表達與代碼的表達&#xff0c;發覺torch.nn.Linear的數學表達與我想象的有點不同&#xff0c;于是思索了一番。 眾多周知&#xff0c;torch.nn.Linear作為全連接層&#xff0c;將下一層的每個結點與上一層的每一節點相連&#xff0c;用…

Leetcode47: Palindrome Linked List

Given a singly linked list, determine if it is a palindrome. 推斷一個鏈表是不是回文的&#xff0c;一個比較簡單的辦法是把鏈表每一個結點的值存在vector里。然后首尾比較。時間復雜度O(n)。空間復雜度O(n)。 /*** Definition for singly-linked list.* struct ListNode {…

內存顆粒位寬和容量_SDRAM的邏輯Bank與芯片容量表示方法

1、邏輯Bank與芯片位寬講完SDRAM的外在形式&#xff0c;就該深入了解SDRAM的內部結構了。這里主要的概念就是邏輯Bank。簡單地說&#xff0c;SDRAM的內部是一個存儲陣列。因為如果是管道式存儲(就如排隊買票)&#xff0c;就很難做到隨機訪問了。陣列就如同表格一樣&#xff0c;…

[Unity菜鳥] Time

1. Time.deltaTime 增量時間 以秒計算&#xff0c;完成最后一幀的時間(秒)(只讀) 幀數所用的時間不是你能控制的。每一幀都不一樣&#xff0c;游戲一般都是每秒60幀&#xff0c;也就是updata方法調用60次&#xff08;假如你按60幀來算 而真實情況是不到60幀 那么物體就不會運動…

【轉】七個例子幫你更好地理解 CPU 緩存

我的大多數讀者都知道緩存是一種快速、小型、存儲最近已訪問的內存的地方。這個描述相當準確&#xff0c;但是深入處理器緩存如何工作的“枯燥”細節&#xff0c;會對嘗試理解程序性能有很大幫助。在這篇博文中&#xff0c;我將通過示例代碼來說明緩存是如何工作的&#xff0c;…

Pytorch——對應點相乘和矩陣相乘

1. 點乘&#xff0c;對應元素相乘&#xff0c;不求和 import torcha torch.Tensor([[1,2], [3,4], [5,6]]) b1 a.mul(a)// b2a*a b1 Out[79]: tensor([[ 1., 4.],[ 9., 16.],[25., 36.]]) b2 Out[80]: tensor([[ 1., 4.],[ 9., 16.],[25., 36.]]) 以上兩種方法都可以表…

mysql初始化錯誤【一】Can't find error-message file '/usr/local/mysql/errmsg.sys'

環境&#xff1a;CentOS 7.2MySQL 5.7.18從mysql官方網站下載rpm包到服務器本地&#xff0c;依次安裝下面的RPM包&#xff1a;mysql-community-common-5.7.18-1.el7.x86_64.rpmmysql-community-server-5.7.18-1.el7.x86_64.rpmmysql-community-client-5.7.18-1.el7.x86_64.rpmm…