正则表达式匹配文档中的url并输出到文档(python)

import re

#打开文档
file_open = open(r"文档路径","r",encoding='utf-8')
file_open2 = open(r"文档路径",'r',encoding='utf-8')
#read()读取文件所有内容,以字符串形式输出
s = file_open.read()
ss = file_open2.read()
#正则表达式,匹配的是带.int.的一个链接,如果要改成其他的url直接修改表达式,再用正则表达式在线工具测试一下是否正确就行
regular = "(http[s]?\://[a-zA-Z0-9\./&\=\:\-]+\.int\.[a-zA-Z0-9\./&\=\:\-]+)"
#findall找出文档所有匹配regular的数据,已列表形式输出
result_1 = re.findall(regular,s)
result_2 = re.findall(regular,ss)
#两份文档的匹配数据相加成一个列表
result = result_1 + result_2
#打开文件,写入数据
file = open(r"文档路径",'w')
#对匹配结果去重写入文档
for i in set(result):
    file.write(i+'\n')
print(result)
#关闭文档
file_open.close()
file_open2.close()
file.close()

你可能感兴趣的:(正则表达式匹配文档中的url并输出到文档(python))