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']
广告
© . All rights reserved.