如何使用 Python 正則表示式從文字中提取日期?
我們首先需要了解一些正則表示式的基本知識,因為我們會用到它們。在正則表示式中宣告模式的方法有很多,這可能會使它們看起來很複雜,但實際上非常簡單。正則表示式是用於匹配符合該模式的字串的模式。您需要閱讀以下文章來了解正則表示式是如何工作的。
在學習編碼時,您可能會經常需要從給定的文字中提取日期。如果您正在自動化一個Python指令碼,並且需要從 CSV 檔案中提取特定的數字,如果您是資料科學家,並且需要從給定的模式中分離複雜的日期,或者如果您是 Python 愛好者,並且想要了解有關字串和數字資料型別的更多資訊,那麼您一定會發現這篇文章很有用。
預計您已經熟悉正則表示式的基本知識。
示例 1
我們將僅使用基本符號來為日期建立正則表示式模式。我們的目標是匹配包含日、月、年或日、月和年的日期,其中日和月的元素有兩個數字,年的元素有四個數字。現在讓我們分步構建模式。
正如您可能猜到的那樣,d 將匹配數字。我們需要在其中提供數字 2 來匹配只有 2 位數字的字串。因此,“d2”將匹配任何只有 2 位數字的字串。日、月和年的模式分別為 d2、d2 和 d4。這三個必須用“/”或“-”連線在一起。
最新的正則表示式模式是“d2”後跟“d2”和“d4”。
現在問題部分已經完成,剩下的任務就容易了。

輸入 1
import re #Open the file that you want to search f = open("doc.txt", "r") #Will contain the entire content of the file as a string content = f.read() #The regex pattern that we created pattern = "\d{2}[/-]\d{2}[/-]\d{4}" #Will return all the strings that are matched dates = re.findall(pattern, content)
需要注意的是,我們的正則表示式模式也將提取不正確的日期,例如 40/32/2019。最終程式碼必須修改為如下所示
輸入 2
import re #Open the file that you want to search f = open("doc.txt", "r") #Will contain the entire content of the file as a string content = f.read() #The regex pattern that we created pattern = "\d{2}[/-]\d{2}[/-]\d{4}" #Will return all the strings that are matched dates = re.findall(pattern, content) for date in dates: if "-" in date: day, month, year = map(int, date.split("-")) else: day, month, year = map(int, date.split("/")) if 1 <= day <= 31 and 1 <= month <= 12: print(date) f.close()
輸入文字
例如,如果文字檔案的內容如下所示
My name is XXX. I was born on 07/12/2001 in YYY city. I graduated from ZZZ college on 07-28-2019.
輸出
07/04/1998 09-05-2019
示例 2
import datetime from datetime import date import re s = "Jason's birthday is on 2002-07-28" match = re.search(r'\d{4}-\d{2}-\d{2}', s) date = datetime.datetime.strptime(match.group(), '%Y-%m-%d').date() print (date)
輸出
2002-07-28
結論
透過以上討論,我們發現了各種Python 函式,用於從給定的文字中提取日期。毫無疑問,正則表示式模組是我們個人最喜歡的。您可能會反駁說,其他方法,例如split() 函式,會導致更快的執行速度以及更簡單、更易於理解的程式碼。但是,如前所述,它不會產生負值(關於方法 2),也不會對沒有空格與其他字元分隔的浮點數起作用,例如“25.50k”(關於方法 2)。此外,在日誌解析方面,速度基本上是一個無用的指標。您現在可以理解為什麼在所有這些選項中,正則表示式是我個人的首選。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP