print(‘輸小了’)
else:
print(‘猜對了’)
break
print(‘猜了次數是:’,count)
效果圖:
按照詩句格式輸出詩詞
原來格式:
人生得意須盡歡,莫使金樽空對月。
天生我材必有用,千金散盡還復來。
輸出效果:
設計思路:
·將所有標點符號替換為\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個單詞
我們來看看實現效果:
步驟拆分:
首先,將文字內容統一為小寫,使用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路徑資訊
這個功能目的主要是替換函式 及 自頂向下的設計思想。
實現的效果:
對整個功能拆分為如下過程:
首先,提取頁面所有元素;
其次,提取圖片的url路徑;
然後,將路徑資訊輸出顯示;
最後,將這些路徑儲存到檔案中。
我們把上面幾個步驟,每個步驟封裝成一個函式,最後main()函式進行呼叫,其中提取圖片的url路徑為核心。
提取頁面所有元素
涉及到知識點:檔案開啟、讀取及關閉。
def gethtmllines(htmlpath):
#檔案開啟
f=open(r,‘htmlpath’,encoding=‘utf-8’)
#檔案讀取
ls=f。readlines()
#檔案關閉
f。close()
return ls
提取圖片的url路徑
原始碼:
知識點:列表形式存放擷取後的地址;列表的切割,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自動化測試學習交流群》
給大家:
請關注+私信回覆:
"頭條"
就可以免費拿到軟體測試學習資料,同時進入群學習交流~~