【问题标题】:Removing the date at the end of a string (different date formats)删除字符串末尾的日期(不同的日期格式)
【发布时间】:2022-01-07 12:24:09
【问题描述】:

我正在尝试删除字符串末尾的日期。我遇到的问题是日期的格式不同,我似乎找不到正确删除它的最佳方法。我到目前为止的代码如下。

text1 = "Hi im some text 1.31. dec. 2020"
text2 = "Hi im some text 2.May, 25, 2019"

def remove_date_from_end(initial_text):
    matches = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
               "Nov", "Dec", "dec"]
    for match in matches:
        if match in initial_text[-14:]:
            print("Found Date in Answer")
            initial_text = initial_text.split(match)[0]
            return initial_text
    return initial_text

print(remove_date_from_end(text1))
print(remove_date_from_end(text2))

输出:

Found Date in Answer
Hi im some text 1.31.
Found Date in Answer
Hi im some text 2.

text2 的输出是正确的,但我似乎无法弄清楚如何让 text1 正确显示为“Hi im some text 1”。

我不确定是否有可能处理此问题的库。据我所知,有几种不同的日期格式。

【问题讨论】:

  • 我想我可以用大量的 if 语句解决这个问题,但我希望有更好的方法。
  • 你知道你需要处理的所有日期格式是什么吗?
  • 日期是否总是在字符串的最后 14 个字符中?
  • 是的,到目前为止我遇到的所有示例都在字符串的最后 14 个字符中

标签: python string date format


【解决方案1】:

你可以使用正则表达式

import json
from re import search, IGNORECASE
from calendar import month_abbr
from datetime import datetime

text1 = "Hi im some text 1.31. dec. 2020"
text2 = "Hi im some text 2.May, 25, 2019"

formats = [
    (
        '{month}, \d{{1,2}}, \d{{4}}',
        '%b, %d, %Y'
    ),
    (
        '\d{{1,2}}\. {month}. \d{{4}}',
        '%d. %b. %Y'
    ),
]


def find_date(text):
    for fmt in formats:
        for x in [fmt[0].format(month=x) for x in month_abbr if x]:
            if (x := search(x, text, IGNORECASE)):
                return {
                    'text': text[:x.start()],
                    'date': datetime.strptime(x.group(0), fmt[1]).date(),
                }

print(find_date(text1))
print(find_date(text2))

【讨论】:

  • 好建议。看起来它的输出不太正确。我看到输出为:1.31。十二月2020 和 2.May, 25, 2019. 预期输出将是 Hi im some text 1. and Hi im some text 2. 看起来正则表达式可能是答案。不过这对我来说很陌生。
  • @user3571198 - 我在正则表达式中犯了一个错误并包含了第一个数字:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多