Python:如何判断一个url是以http开头的?
比如一个文本test.txt,里面的内容为:
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, 从开头匹配字符串,如果匹配到返回匹配到的对象。没有匹配到返回None。
有没有更简单的方式呢?
#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,那么有没有判断结尾的呢?
答案是当然的。
#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)
这里要注意的是,每行结束会有一个换行符,因此要替换掉。
虽然从代码行数上,区别不是太大,但是从方法名称的理解上,startswith和endswith,更容易一些。
如果要匹配多个字符怎么办?
比如文本内容为:
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)
只需要传参数为元组,包含要匹配的字串即可。
网友评论