如何通过Stanford CoreNLP服务器设置SUTime的参考时间?
在Stanford CoreNLP服务器中为SUTime设置参考时间的方法
完全可以实现!Stanford CoreNLP服务器支持通过请求参数动态指定SUTime的参考日期,这样就能让像"tomorrow"这类相对时间被正确解析成具体日期。下面是具体的实现步骤和Python代码示例:
核心原理
SUTime允许通过配置参数sutime.referenceDate来设置参考时间,你只需要在向服务器发送标注请求时,把这个参数加入到请求的properties中即可,参数值需要是ISO 8601格式的日期字符串(比如2024-05-20)。
Python客户端实现示例
假设你的CoreNLP服务器运行在http://localhost:9000,可以用requests库发送POST请求,代码如下:
import datetime import requests import json # 生成当前日期的ISO格式字符串作为参考时间 reference_date = datetime.datetime.now().strftime("%Y-%m-%d") # 待处理的文本 text = "I need a desk for tomorrow from 2pm to 3pm" # 构造请求数据 request_data = { "text": text, "properties": { "annotators": "tokenize,ssplit,pos,lemma,ner,sutime", "outputFormat": "json", "sutime.referenceDate": reference_date, # 可选:开启时间范围标注 "sutime.markTimeRanges": "true" } } # 发送请求到CoreNLP服务器 response = requests.post( url="http://localhost:9000/annotate", headers={"Content-Type": "application/json"}, data=json.dumps(request_data) ) # 解析返回结果 result = response.json() # 提取SUTime标注的时间信息 for sentence in result["sentences"]: print("时间标注结果:") for timex in sentence.get("timexAnnotations", []): print(f"文本片段: {timex['text']}") print(f"标准化时间: {timex['value']}") print("---")
关键说明
- 确保你的annotators列表中包含
sutime,否则服务器不会进行时间标注。 sutime.referenceDate的值必须是YYYY-MM-DD格式,SUTime会基于这个日期解析相对时间词(比如tomorrow、next week等)。- 如果需要更精确的参考时间(包含时分秒),也可以使用
YYYY-MM-DDTHH:MM:SS格式,比如2024-05-20T10:30:00。
这样处理后,服务器返回的结果里,"tomorrow"就会被解析为当前日期的下一天,结合后面的时间段,就能得到完整的标准化时间范围啦。
内容的提问来源于stack exchange,提问作者devavratrk
相关产品推荐
相关产品推荐

