簡體   English   中英

循環遍歷正則表達式模式列表/字典並提取字符串的 Pythonic 方式

[英]Pythonic way of looping through a list/dict of regex patterns and extracting string

作為多年來一直在 R 中編寫所有內容的人,我仍然不確定我是否在 Python 中以最佳方式處理迭代/列表推導式。 例如,假設我有字符串:

string = "Imported as of 1 Jan 2020"

我想從字符串中構建一個日期對象,其中我的模式存儲到 R 中的named list或 python 中的dict如下:

dates_r =  list(
    day = '[0-9]{1,2}(?=\\s+)',
    month = '(\\w+)(?=(\\s)[0-9]{4})',
    year = '[0-9]{4}$'
)

dates_py = {
    'day':r'[0-9]{1,2}(?=\s+)',
    'month':r'(\w+)(?=(\s)[0-9]{4})',
    'year':r'[0-9]{4}$'
}

在 RI 中可以簡單地

> dates_out_r <- mapply(stringi::stri_extract_all_regex, pattern = dates_r, str = string, simplify = F)
> dates_out_r 
$day
[1] "1"

$month
[1] "Jan"

$year
[1] "2020"

有沒有比我目前在 python 中做的更好的方法?

dates_py = {
    'day': r'[0-9]{1,2}(?=\s+)',
    'month': r'(\w+)(?=(\s)[0-9]{4})',
    'year': r'[0-9]{4}$'
}

dates_out = {}

for key, value in dates_py.items():
    rgx = re.compile(value)
    dates_out[key] = re.search(rgx, date_str)[0]
dates_out
{'day': '1', 'month': 'February', 'year': '2020'}

你可以使用字典理解
它本質上與for循環相同,但更短

d = {k: re.search(regex, string)[0] for k, regex in dates_py.items()}

還有一種相當於 mapply,但看起來很丑(至少在我的實現中)

dict(map(lambda k, regex: (k, re.search(regex, string)[0]), dates_py.keys(), dates_py.values()))

還要注意,這種情況下re.search(...) is None處理,處理會添加更多的事件代碼,這對於單行來說並不酷

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM