Python中怎么判斷一個(gè)url是否以http開頭

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)Python中怎么判斷一個(gè)url是否以http開頭,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

站在用戶的角度思考問題,與客戶深入溝通,找到鞏義網(wǎng)站設(shè)計(jì)與鞏義網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、域名注冊(cè)、雅安服務(wù)器托管、企業(yè)郵箱。業(yè)務(wù)覆蓋鞏義地區(qū)。

Python:如何判斷一個(gè)url是以http開頭的?

比如一個(gè)文本test.txt,里面的內(nèi)容為:

http://www.sogou.com
this is a url
this is http://www.sogou.com address

第一種方式是,判斷包含:

#encoding: utf-8
 
with open("test.txt", "r") as f:
content = f.readlines()
for line in content:
 if "http" in line:
 print(line)

輸出為:

http://www.sogou.com
this is http://www.sogou.com address

如果只獲取以http開頭的,那么:

#encoding: utf-8
import re
with open("test.txt", "r") as f:
content = f.readlines()
for line in content:
 r = re.match("http", line)
 if r != None:
 print(line)

輸出為:

http://www.sogou.com

re.match, 從開頭匹配字符串,如果匹配到返回匹配到的對(duì)象。沒有匹配到返回None。

有沒有更簡(jiǎn)單的方式呢?

#encoding: utf-8
with open("test.txt", "r") as f:
 content = f.readlines()
 for line in content:
 if line.startswith("http"):
 print(line)

同樣輸出為:

http://www.sogou.com

既然有startswith,那么有沒有判斷結(jié)尾的呢?

答案是當(dāng)然的。

#encoding: utf-8
with open("test.txt", "r") as f:
 content = f.readlines()
 for line in content:
 if line.replace("\n","").endswith("com"):
 print(line)

這里要注意的是,每行結(jié)束會(huì)有一個(gè)換行符,因此要替換掉。

雖然從代碼行數(shù)上,區(qū)別不是太大,但是從方法名稱的理解上,startswith和endswith,更容易一些。

如果要匹配多個(gè)字符怎么辦?

比如文本內(nèi)容為:

http://www.sogou.com
this is a url
this is http://www.sogou.com address
ftp://www.sogou.com
#encoding: utf-8
with open("test.txt", "r") as f:
 content = f.readlines()
 for line in content:
 if line.startswith(("http", "ftp")):
 print(line)

只需要傳參數(shù)為元組,包含要匹配的字串即可。

上述就是小編為大家分享的Python中怎么判斷一個(gè)url是否以http開頭了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

文章題目:Python中怎么判斷一個(gè)url是否以http開頭
分享地址:http://muchs.cn/article2/pishic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、網(wǎng)站導(dǎo)航App開發(fā)、營(yíng)銷型網(wǎng)站建設(shè)用戶體驗(yàn)、網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁(yè)設(shè)計(jì)公司