gpt4 book ai didi

groovy - 使用 stanford nlp 查找日期及其在字符串中的位置

转载 作者:行者123 更新时间:2023-12-04 02:51:07 24 4
gpt4 key购买 nike

我需要找到字符串中的日期及其位置。考虑示例字符串

“有趣的日期是从今天开始的 4 天,是今年的 7 月 20 日,另一个日期是 1997 年 2 月 18 日”

我需要输出(假设今天是 2013-07-14)
2013-07-17,第25位
2013-07-20,第56位
1997-02-18,第 93 位

我已经设法编写代码来获取被识别为日期的字符串的各个部分。需要增强/更改它以实现上述输出。任何提示或帮助表示赞赏:

    Properties props = new Properties();
AnnotationPipeline pipeline = new AnnotationPipeline();
pipeline.addAnnotator(new PTBTokenizerAnnotator(false));
pipeline.addAnnotator(new WordsToSentencesAnnotator(false));
pipeline.addAnnotator(new POSTaggerAnnotator(false));
pipeline.addAnnotator(new TimeAnnotator("sutime", props));

Annotation annotation = new Annotation("The interesting date is 4 days from today and it is 20th july of this year, another date is 18th Feb 1997");
annotation.set(CoreAnnotations.DocDateAnnotation.class, "2013-07-14");
pipeline.annotate(annotation);
List<CoreMap> timexAnnsAll = annotation.get(TimeAnnotations.TimexAnnotations.class);
timexAnnsAll.each(){
println it
}

使用上面的代码,我得到的输出是:
从今天开始还有 4 天
今年7月20日
1997 年 2 月 18 日

编辑::
通过以下更改设法获取日期部分

timexAnnsAll.each(){it ->  
Timex timex = it.get(TimeAnnotations.TimexAnnotation.class);
println timex.val + " from : $it"
}

现在的输出是:
2013-07-18 来自:从今天起4天
2013-07-20 起于:今年7月20日
1997-02-18 来自:1997 年 2 月 18 日

我现在需要解决的就是找到原始字符串中日期的位置。

最佳答案

annotation.get(TimeAnnotations.TimexAnnotations.class)返回的列表中的每个CoreMap都是一个Annotation,您可以获取它的其他属性,例如列表 token ,每个 token 存储字符偏移信息。所以你可以这样结束你的例子:

List<CoreMap> timexAnnsAll = annotation.get(TimeAnnotations.TimexAnnotations.class);
for (CoreMap cm : timexAnnsAll) {
List<CoreLabel> tokens = cm.get(CoreAnnotations.TokensAnnotation.class);
System.out.println(cm +
" [from char offset " +
tokens.get(0).get(CoreAnnotations.CharacterOffsetBeginAnnotation.class) +
" to " + tokens.get(tokens.size() -1)
.get(CoreAnnotations.CharacterOffsetEndAnnotation.class) + ']');
/* -- This shows printing out each token and its character offsets
for (CoreLabel token : tokens) {
System.out.println(token +
", start: " + token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class) +
", end: " + token.get(CoreAnnotations.CharacterOffsetEndAnnotation.class));
}
*/
}

那么输出是:

4 days from today [from char offset 24 to 41]
20th july of this year [from char offset 52 to 74]
18th Feb 1997 [from char offset 92 to 105]

关于groovy - 使用 stanford nlp 查找日期及其在字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17634675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com