从字符串中提取格式不一致的日期(日期解析,NLP)

时间:2010-08-10 01:16:05

标签: perl date nlp

我有一大堆文件,其中一些文件中嵌入了日期。日期的格式不一致,往往不完整,例如“Aug06”,“Aug2006”,“2006年8月”,“08-06”,“01-08-06”,“2006”,“011004”等。除此之外,一些文件名有无关的数字看起来有点像日期,例如“20202010”。

简而言之,日期通常是不完整的,有时不存在,格式不一致,并且嵌入在带有其他信息的字符串中,例如“报告Aug06.xls”。

是否有任何可用的Perl模块可以从这样的字符串中猜测日期?它不一定是100%正确,因为它将由人工验证,但我正在努力使这个人尽可能简单,并且有成千上万的条目要检查:)

3 个答案:

答案 0 :(得分:3)

Date :: Parse肯定会成为你答案的一部分 - 这个数字会产生一个随机格式化的类似日期的字符串,并从中产生一个实际可用的日期。

问题的另一部分 - 文件名中的其他字符 - 非常不寻常,以至于您不太可能发现其他人已为您打包模块。

在没有看到更多样本数据的情况下,实际上只能猜测,但我首先要确定可能的或可能的“日期部分”候选人。

这是使用Date :: Parse的一个令人讨厌的暴力示例(一个更聪明的方法会使用regex-en列表来尝试和识别日期位 - 我很高兴燃烧cpu周期,虽然不太认为这么难!)

!/usr/bin/perl
use strict;
use warnings;
use Date::Parse;

my @files=("Report Aug06.xls", "ReportAug2006", "Report 11th September 2006.xls", 
           "Annual Report-08-06", "End-of-month Report01-08-06.xls", "Report2006");

# assumption - longest likely date string is something like '11th September 2006' - 19 chars
# shortest is "2006" - 4 chars.
# brute force all strings from 19-4 chars long at the end of the filename (less extension)
# return the longest thing that Date::Parse recognises as a date



foreach my $file (@files){
  #chop extension if there is one
  $file=~s/\..*//;
  for my $len (-19..-4){
    my $string = substr($file, $len);
    my $time = str2time($string);
    print "$string is a date: $time = ",scalar(localtime($time)),"\n" if $time;
    last if $time;
    }
  }

答案 1 :(得分:0)

Date::Parse做你想做的事。

答案 2 :(得分:0)

DateTime::Format::Natural看起来像是这份工作的候选人。我不能亲自担保,但它有good reviews