您現在的位置是:首頁 > 農業

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

由 Atstudy網校 發表于 農業2022-01-09
簡介案例名稱·計算圓形面積·輸入字元並倒序輸出·猜數字遊戲·按照詩句格式輸出詩詞·統計文字中出現次數最多的10個單詞(txt)·web頁面元素提取計算圓形面積知識點:print 結合format()函式實現輸出格式

累積頻率如何計算

最近系統學習了一遍python基礎知識,學著學著靈光一閃,想到有沒有快速掌握知識的方法。一般正常的邏輯是邊看基礎知識邊練習案例,是一個書由厚變薄的過程。不過現在節奏這麼快,尤其是網際網路公司,排除週末在家看孩子的時間,幾乎沒有時間和精力再進行深度學習,所以這篇文章就誕生了。

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

本文透過案例入手直接結合python知識點,可以快速掌握python基礎知識點。

案例名稱

·計算圓形面積

·輸入字元並倒序輸出

·猜數字遊戲

·按照詩句格式輸出詩詞

·統計文字中出現次數最多的10個單詞(txt)

·web頁面元素提取

計算圓形面積

知識點:print 結合format()函式實現輸出格式。

固定的公式:

print(<輸出字串模板>。format(<變數1>,<變數2>,<變數3>))

實現程式碼:

r = 25 # 圓的半徑是25

area = 3。1415 * r * r #圓的公式

print(area)

print(‘{:。2f}’。format(area) ) # 只輸出兩位小數

新手易錯點:

format前的字串模板格式‘{:。2f}’ 經常會寫錯,其中一個{}對應一個format裡面的引數。

輸入字元並倒序輸出

核心思想:找到最後一個元素並輸出。

知識點:

·輸入使用input函式

·計算長度使用len()函式

·輸出函式結尾使用end=’‘,作用在輸出的字元後方新增空字串

#輸入文字

s=input(‘請輸入一段文字:’)

#計算輸入內容的長度並賦值給i

i=len(s)-1

#倒序迴圈輸出

while i>=0:

print(s[i],end=‘’)

i=i-1

實現效果:

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

猜數字遊戲

隨機產生一個數字,並判斷輸入的數字和這個隨機數直到猜測成功。

知識點:

1。使用random。randint()函式生成一個隨機數字

2。while()迴圈,當未滿足條件一直執行,滿足條件break跳出迴圈

3。輸入數字eval函式結合input,將字串型別轉換成整數

4。if 三分支條件判斷,if elif else 格式

實現程式碼:

import random

#生成隨機數

a=random。randint(0,1000)

#統計次數

count=0

while True:

number=eval(input(‘請輸入0到1000之間的一個數:’))

count=count+1

#判斷比較兩個數

if number>a:

print(‘輸大了’)

elif number

print(‘輸小了’)

else:

print(‘猜對了’)

break

print(‘猜了次數是:’,count)

效果圖:

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

按照詩句格式輸出詩詞

原來格式:

人生得意須盡歡,莫使金樽空對月。

天生我材必有用,千金散盡還復來。

輸出效果:

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

設計思路:

·將所有標點符號替換為\n

·文字居中對齊顯示

知識點:

1。替換函式line。replace(變數名,要替換的值)

2。居中對齊line。center(寬度)

3。函式呼叫,將文字變數txt傳入替換函式linesplit中

txt = ‘’‘

人生得意須盡歡,莫使金樽空對月。

天生我材必有用,千金散盡還復來。

’‘’

#定義一個函式,實現將標點符號替換為\n

def linesplit(line):

plist = [‘,’, ‘!’, ‘?’, ‘,’, ‘。’, ‘!’, ‘?’]

for p in plist:

line=line。replace(p,‘\n’)

return line。split(‘\n’)

linewidth = 30 # 預定的輸出寬度

#定義一個函式,實現居中對齊

def lineprint(line):

global linewidth

print(line。center(linewidth))

#呼叫函式

newlines=linesplit(txt)

for newline in newlines:

lineprint(newline)

統計文字中出現次數最多的10個單詞

我們來看看實現效果:

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

步驟拆分:

首先,將文字內容統一為小寫,使用lower()函式;

再次,將文字中特殊字元替換為空格,replace()函式;

按空格將文字進行切割,使用split()函式;

統計單詞出現的次數;

按頻率從大到小排序 sort()函式;

按照固定格式輸出 ,使用format()函式。

按照上面的步驟實現程式碼。

首先,將文字內容統一為小寫,使用lower()函式:

def gettxt():

#讀取檔案

txt=open(‘hamlet。txt’,‘r’)。read()

txt=txt。lower()

再次,將文字中特殊字元替換為空格,replace()函式:

for ch in ‘’!“#$%&()*+,-。/:;<=>?@[\\]^_‘{|}~‘:’

txt=txt。replace(‘’)

return txt

按空格將文字進行切割,使用split()函式:

hmlttxt=gettxt()

words=hmlttxt。split()

統計單詞出現的次數:

counts=0

for word in words:

counts[word]=counts。get(word,0)+1 #對word出現的頻率進行統計,當word不在words時,返回值是0,當word在words中時,返回+1,以此進行累計計數

按頻率從大到小排序 items()sort()排序函式:

items=list(counts。items())

items。sort(key=lambada x:x[1],reverse=True)

上面的x可以是任意字母,reverse=True倒序排序,預設升序。

按照固定格式輸出 ,使用format()函式:

for i in range(10)

word,count=item[i]

print(‘{0:<10}{1:>5}’。format(word,count))

完整程式碼:

# 首先,將文字內容統一為小寫,使用lower()函式

def gettxt():

txt=open(‘hamlet。txt’,‘r’)。read()

txt=txt。lower()

# 將文字中特殊字元替換為空格,replace()函式

for ch in ‘!”#$%&()*+,-。/:;<=>?@[\\]^_‘{|}~’:

txt=txt。replace(ch,‘’)

return txt

# 按空格將文字進行切割,使用split()函式

hamlettxt=gettxt()

words=hamlettxt。split()

# 統計字數

counts={}

for word in words:

counts[word]=counts。get(word,0)+1

# 按頻率從大到小排序 sort()函式

items=list(counts。items())

items。sort(key=lambda x:x[1],reverse=True)

# 按照固定格式輸出 ,使用format()函式

for i in range(10):

word, count=items[i]

print(“{0:<10},{1:>5}”。format(word,count))

web頁面元素提取圖片url路徑資訊

這個功能目的主要是替換函式 及 自頂向下的設計思想。

實現的效果:

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

對整個功能拆分為如下過程:

首先,提取頁面所有元素;

其次,提取圖片的url路徑;

然後,將路徑資訊輸出顯示;

最後,將這些路徑儲存到檔案中。

我們把上面幾個步驟,每個步驟封裝成一個函式,最後main()函式進行呼叫,其中提取圖片的url路徑為核心。

提取頁面所有元素

涉及到知識點:檔案開啟、讀取及關閉。

def gethtmllines(htmlpath):

#檔案開啟

f=open(r,‘htmlpath’,encoding=‘utf-8’)

#檔案讀取

ls=f。readlines()

#檔案關閉

f。close()

return ls

提取圖片的url路徑

原始碼:

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

知識點:列表形式存放擷取後的地址;列表的切割,split()函式。

def geturl(ls):

urls=[]

for line in ls:

if ‘img’ in line:

url=line。split(‘alt="自動化測試工程師必備:6個案例教你快速掌握Python基礎知識" data-isLoading="0" src="/static/img/blank.gif" data-src=’)[-1]。split(‘“’)[1]

urls。append(url)

將路徑資訊輸出顯示

知識點:for迴圈將路徑資訊輸出。

for迴圈將路徑資訊輸出

def show(urls):

count=0

for url in urls:

print(‘第{:2}個url{}’。format(count,url))

count+=1

將這些路徑儲存到檔案中

知識點:檔案的寫入。

def save(filepath,urls):

f=open(filepate,‘w’)

for url in urls:

f。write(url+‘\n’)

f。close()

main()函式,將上面的函式進行組合

def main():

inputfile = ‘nationalgeographic。html’

outputfile = ‘nationalgeographic-urls。txt’

htmlLines = getHTMLlines(inputfile)

imageUrls = extractImageUrls(htmlLines)

showResults(imageUrls)

saveResults(outputfile, imageUrls)

最終程式碼:

# Example_8_1。py

#1。 按行讀取頁面所有內容

def getHTMLlines(htmlpath):

f = open(htmlpath, ”r“, encoding=‘utf-8’)

ls = f。readlines()

f。close()

return ls

#2。 提取http路徑

def extractImageUrls(htmllist):

urls = []

for line in htmllist:

if ‘img’ in line:

url = line。split(‘alt="自動化測試工程師必備:6個案例教你快速掌握Python基礎知識" data-isLoading="0" src="/static/img/blank.gif" data-src=’)[-1]。split(‘”’)[1]

print

if ‘http’ in url:

urls。append(url)

return urls

#3。 輸出連結地址

def showResults(urls):

count = 0

for url in urls:

print(‘第{:2}個URL:{}’。format(count, url))

count += 1

#4。 儲存結果到檔案

def saveResults(filepath, urls):

f = open(filepath, “w”)

for url in urls:

f。write(url+“\n”)

f。close()

def main():

inputfile = ‘nationalgeographic。html’

outputfile = ‘nationalgeographic-urls。txt’

htmlLines = getHTMLlines(inputfile)

imageUrls = extractImageUrls(htmlLines)

showResults(imageUrls)

saveResults(outputfile, imageUrls)

main()

一句話總結:這個小案例可熟練掌握檔案的讀、寫操作,可以體會函式的思想以及split()函式的拆分。

總結

上面主要介紹了python的基礎功能,建議大家熟練掌握,主要知識點如下:

·input函式實現輸入

·print結合format()函式對結果進行輸出

·計算字串長度len()函式

·使用random。randint()函式生成隨機數字

·eval函式結合input,將字串型別轉換成整數

·if 三分支條件判斷,if elif else 格式

·替換函式line。replace(變數名,要替換的值)

·文字內容統一為小寫,使用lower()函式

·文字中特殊字元替換為空格,replace()函式

·文字進行切割,使用split()函式

·從大到小排序 sort()函式

**文末福利——推薦一個

《Python自動化測試學習交流群》

給大家:

請關注+私信回覆:

"頭條"

就可以免費拿到軟體測試學習資料,同時進入群學習交流~~

自動化測試工程師必備:6個案例教你快速掌握Python基礎知識

推薦文章