[英]Searching for a specific string in a cell, and then returning only specific values after the string
[英]Returning specific values in a string of different format
如何讓python以不同格式的字符串自動搜索某種特定類型的數據(例如日期)?
示例輸入:
"-rwxr-xr-x 1 user usergrp 1632 Feb 26 11:03 Desktop/Application"
"Desktop/Application,1632,26/02"
"26/02/19 - Desktop/Application - 1632"
這些示例的輸出應為26 Feb 19
。
相關但不同: 將“未知格式”字符串轉換為日期時間對象?
這個問題是不同的,因為字符串不僅僅是日期,而是嵌入在字符串中。 我將此問題視為“如何在格式不一致的字符串中查找日期?”
我使用dateparser 0.7.1 ,文檔可以在這里找到。 因為字符串的格式未知並且可能與每個字符串不同,所以我計算字符串中的所有字符 ngram,然后將它們解析為日期。 然后將最常見的日期作為正確的輸出返回。 這是一種緩慢且低效的方法,但它是我能針對此處的要求提出的最佳方法:
代碼如下:
from collections import Counter
import dateparser
def extract_date(min_date_length=5, max_date_length=15, min_year_value=2000, max_year_value=2020):
val = "Feb 26 11:03 Desktop/Application"
val = "Desktop/Application,1632,26/02"
val = "26/02/19 - Desktop/Application - 1632"
grams = []
for n in range(min_date_length, max_date_length):
grams.extend(val[i:i + n] for i in range(len(val) - n + 1))
dates = []
for gram in grams:
out = dateparser.parse(gram)
if out and min_year_value <= out.year <= max_year_value:
dates.append(out)
date, _count = Counter(dates).most_common(1)[0]
print(date)
return date
if __name__ == "__main__":
extract_date()
這個怎么運作:
min_date_length
和max_date_length
之間)的所有字符 ngram,並且日期通常不能任意長或比默認值 5 短得多(盡管它是可能的,例如如果日期格式是1/1
以 1 月 1 日為例)dateparser.parse
將dateparser.parse
解析為日期,並忽略所有無法解析的內容1632
被視為"Desktop/Application,1632,26/02"
)此解決方案適用於問題中包含的三個示例。 再次注意,這是一種非常低效的方法,它可能不適用於所有情況(例如,對於字符串中的多個日期,它會中斷)。
更有效的方法是使用正則表達式從每個字符串中提取日期字符串,然后使用datetime.strptime
。 請參閱strftime() 和 strptime() 行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.