- 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.tw 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.tw']
廣告