使用 NLTK 识别字符串中的日期

Identifying dates in strings using NLTK

我正在尝试确定日期是否出现在任意字符串中。这是我的代码:

import nltk

txts = ['Submitted on 1st January',
'Today is 1/3/15']

def chunk(t):
    w_tokens = nltk.word_tokenize(t)
    pt = nltk.pos_tag(w_tokens)
    ne = nltk.ne_chunk(pt)
    print ne

for t in txts:
    print t
    chunk(t)

我得到的输出是

Submitted on 1st January
(S (GPE Submitted/NNP) on/IN 1st/CD January/NNP)
Today is 1/3/15
(S Today/NN is/VBZ 1/3/15/CD)

显然没有标记日期。有谁知道如何标记日期?

谢谢

NLTK ne_chunk() 默认不识别日期。您需要先从 nltk_contrib 获取它才能使用 timex.py

我从您的评论 1/1/70 中获取了日期示例,但是如果它们的格式不同,例如 1970/01/20 或 2-,此正则表达式代码也能找到它们21-79

import re
x = 'asdfasdf sdf5sdf asd78fsadf 1/1/70 dfsdg fghdfgh 1970/01/20 gfh5fghh sdfgsdg 2-21-79 sdfgsdgf'
print re.findall(r'\d+\S\d+\S\d+', x)

输出:

['1/1/70', '1970/01/20', '2-21-79']

或者,

y = 'Asdfasdf Ddf5sdf asd78fsadf Jan 3 dfsdg fghdfgh February 10 sdfgsdgf'
print re.findall(r'[A-Z]\w+\s\d+', y) 

输出:

['Jan 3', 'February 10']

NLTK 本身不会检测日期,但会与 Stanford's Named Entity Tagger 结合使用。找到有效工作的正确指令集可能很困难,因此这里有几个链接:

Stanford tagger site - look for downloads: https://nlp.stanford.edu/software/CRF-NER.shtml
Stanford tagger API - http://www.nltk.org/api/nltk.tag.html#nltk.tag.stanford.StanfordTagger

抱歉,最后两个链接不起作用。

这是我使用的代码:

from nltk.tag import StanfordNERTagger
stanfordClassifier = '/path/to/classifier/classifiers/english.muc.7class.distsim.crf.ser.gz'
stanfordNerPath = '/path/to/jar/stanford-ner-2017-06-09/stanford-ner.jar'
st = StanfordNERTagger(stanfordClassifier, stanfordNerPath, encoding='utf8')
result = st.tag(word_tokenize("The date is October 13, 2017"))
print (result)