- Python - 文本处理
- Python - 文本处理介绍
- Python - 文本处理环境
- Python - 字符串不变性
- Python - 排序行
- Python - 重新格式化段落
- Python - 统计段落中令牌
- Python - 二进制 ASCII 转换
- Python - 字符串作为文件
- Python - 反向文件读取
- Python - 过滤重复单词
- Python - 从文本中提取电子邮件
- Python - 从文本中提取 URL
- Python - 美化打印
- Python - 文本处理状态机
- Python - 用大写字母书写并翻译
- Python - 标记化
- Python - 移出停用词
- Python - 同义词和反义词
- Python - 文本翻译
- Python - 单词替换
- Python - 拼写检查
- Python - WordNet 接口
- Python - 文集访问
- Python - 标记单词
- Python - 块和碎片
- Python - 块分类
- Python - 文本分类
- Python - 二元组
- Python - 处理 PDF
- Python - 处理 Word 文档
- Python - 阅读 RSS 源
- Python - 情绪分析
- Python - 搜索和匹配
- Python - 文本堆砌
- Python - 文本换行
- Python - 频率分布
- Python - 文本摘要
- Python - 词干算法
- Python - 受限搜索
Python - 从文本中提取 URL
通过使用正则表达式从文本文件中提取 URL。该表达式获取文本,无论其是否与表达式所指定的模式匹配。为此只使用了 re 模块。
示例
我们可以采用包含部分 URL 的输入文件,并通过以下程序进行处理以提取这些 URL。我们使用 findall() 函数来查找与正则表达式相匹配的所有实例。
输入文件
下面显示了输入文件。其中包含两个 URL。
Now a days you can learn almost anything by just visiting http://www.google.com. But if you are completely new to computers or internet then first you need to leanr those fundamentals. Next you can visit a good e-learning site like - https://tutorialspoint.com to learn further on a variety of subjects.
现在,当我们将上述输入文件采用并通过以下程序进行处理时,我们会获得所需输出,即文件提取出的 URL。
import re
with open("path\url_example.txt") as file:
for line in file:
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', line)
print(urls)
当我们运行上述程序时,我们会获得以下输出 −
['http://www.google.com.'] ['https://tutorialspoint.com']
广告