【问题标题】:How to Know if a Complete Sentence has dates in it?如何知道一个完整的句子中是否有日期?
【发布时间】:2019-11-07 11:50:49
【问题描述】:

我看过一些关于识别可能的字符串是否是日期的帖子,但似乎没有一个帖子涉及句子中是否有潜在的日期。

我使用了 dateutil 解析器函数,它似乎只有在日期是字符串的唯一组成部分时才能有效识别字符串中的日期。

from dateutil.parser import parse

def is_date(string, fuzzy=False):
    """
    Return whether the string can be interpreted as a date.

    :param string: str, string to check for date
    :param fuzzy: bool, ignore unknown tokens in string if True
    """
    try: 
        parse(string, fuzzy=fuzzy)
        return True

    except ValueError:
        return False

>>> is_date("1990-12-1")
True
>>> is_date("foo 1990-12-1 bar")
False

【问题讨论】:

    标签: python parsing


    【解决方案1】:

    你可以使用一个简单的正则表达式模式

    import re
    def is_date(regex, str):
        return bool(re.match(regex, s))
    
    regex = r'.*? \d{4}-\d\d?-\d\d? .*?'
    
    >>> is_date(regex, "foo bar")
    False
    >>> is_date(regex, "1990-12-1")
    True
    >>> is_date(regex, "foo 1990-12-1 bar")
    True
    

    这将匹配格式为“####-#[#]-#[#]”的任何日期,其中方括号中的# 是可选的。您可以修改此正则表达式模式以满足您的需求。

    more about regex

    【讨论】:

      【解决方案2】:

      一种解决方案是拆分字符串,然后测试每个部分,如果任何拆分字符串成功解析为日期,则返回 True。

      def is_date(string, fuzzy=False):
          """
          Return whether the string can be interpreted as a date.
      
          :param string: str, string to check for date
          :param fuzzy: bool, ignore unknown tokens in string if True
          """
          def parse_date(date_string):
              try: 
                  return parse(date_string, fuzzy=fuzzy)
              except ValueError:
                  return False
      
          return any(parse_date(s) for s in string.split())
      
      >>> is_date("1990-12-1")
      True
      
      >>> is_date("foo 1990-12-1 bar")
      True
      
      >>> is_date("foo 1990-13-1 bar")
      False
      
      >>> is_date('Book by appt. for Dec. 31, 2019')
      True  # Both 'Dec.' and '2019' successfully parse to a date.
      
      # But be wary of false positives.
      >>> is_date('I had 2019 hits on my website today')
      True  
      

      【讨论】:

        【解决方案3】:

        一种可能性是检查原始字符串的所有可能(连续)子字符串。该解决方案具有可怕的性能(N^2 次调用 OP 的 is_date),但它不依赖启发式方法来拆分字符串或正则表达式定义中的标记:根据定义,它匹配 iff is_date 将匹配子字符串。

        def get_all_substrings(input_string):
            # From https://stackoverflow.com/questions/22469997/how-to-get-all-the-contiguous-substrings-of-a-string-in-python
            # could be made a generator to save space, but we are not making a performant solution anyway
            length = len(input_string)
            return [input_string[i:j+1] for i in xrange(length) for j in xrange(i,length)]
        
        def contains_date(string):
            for substring in get_all_substrings(string):
                if is_date(substring): return True
            return False
        

        【讨论】:

          猜你喜欢
          • 2012-05-08
          • 1970-01-01
          • 2020-11-09
          • 1970-01-01
          • 2014-04-13
          • 1970-01-01
          • 1970-01-01
          • 2011-12-08
          • 1970-01-01
          相关资源
          最近更新 更多