从结构不均匀的字符串中提取日期

2024-09-27 00:12:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从字符串中提取日期信息。字符串可能如下所示:

  1. 5个月17个小时
  2. 1个月19天
  3. 3个月零1天
  4. 2年1个月零2天
  5. 1年1个月1天1小时

我想摘录:

  1. y=0 m=5 d=0 h=17
  2. y=0 m=1 d=19 h=0
  3. y=0 m=3 d=1 h=0
  4. y=2m=1d=2h=0
  5. y=1m=1d=1h=1

我开始这样做:

publishedWhen = '1 year 1 month and 1 days and 1 hour'

y,m,d,h = 0,0,0,0

if 'day ' in publishedWhen:
    d = int(publishedWhen.split(' day ')[0])

if 'days ' in publishedWhen:
    d = int(publishedWhen.split(' days ')[0])

if 'days ' not in publishedWhen and 'day ' not in publishedWhen:
    d = 0

if 'month ' in publishedWhen:
    m = int(publishedWhen.split(' month ')[0])
    d = int(publishedWhen.replace(publishedWhen.split(' month ')[0] + ' month ','').replace('and','').replace('days','').replace('day',''))

if 'months ' in publishedWhen:
    m = int(publishedWhen.split(' months ')[0])

不过,我知道这段代码有很多bug(有些情况可能没有考虑在内),而且regex可能会产生一些更干净、更有效的代码。这是真的吗?哪个正则表达式可以帮我提取所有这些信息


Tags: and字符串in信息ifnotdaysreplace
1条回答
网友
1楼 · 发布于 2024-09-27 00:12:48

您可以don't have to use re\gular expres{2}ions?并在Python包索引中查看非常丰富的第三方包库

例如,您可以将^{}-用于解析人类可读的日期,将dateutil-用于relative delta object的组合:

from datetime import datetime

import dateparser as dateparser
from dateutil.relativedelta import relativedelta


BASE_DATE = datetime(2018, 1, 1)


def get_relative_date(date_string):
    parsed_date = dateparser.parse(date_string, settings={"RELATIVE_BASE": BASE_DATE})
    return relativedelta(parsed_date, BASE_DATE)


date_strings = [
    "5 months and 17 hours",
    "1 month and 19 days",
    "3 months and 1 day",
    "2 years 1 month and 2 days",
    "1 year 1 month and 1 days and 1 hour"
]

for date_string in date_strings:
    delta = get_relative_date(date_string)
    print(f"y={abs(delta.years)} m={abs(delta.months)} d={abs(delta.days)} h={abs(delta.hours)}")

印刷品:

y=0 m=5 d=0 h=17
y=0 m=1 d=19 h=0
y=0 m=3 d=1 h=0
y=2 m=1 d=2 h=0
y=1 m=1 d=1 h=1

我并不特别喜欢需要用一些基本日期来做delta,并且非常确定有一个包可以直接解析到delta对象中。愿意接受任何建议

相关问题 更多 >

    热门问题