我有一个这样的字符串:

"The dates are from 30 June 2019 to 1 January 2022 inclusive"

我想用spaCy从这个字符串中提取日期.

以下是我到目前为止的功能:

def extract_dates_with_year(text):
    doc = nlp(text)
    dates_with_year = []
    for ent in doc.ents:
        if ent.label_ == "DATE":
            dates_with_year.append(ent.text)
    return dates_with_year

这将返回以下输出:

['30 June 2019 to 1 January 2022']

但是,我希望输出如下:

['30 June 2019', '1 January 2022']

推荐答案

问题是,"to"被认为是日期的一部分.因此,当你执行for ent in doc.ents时,你的循环只有一次迭代,因为"30 June 2019 to 1 January 2022"被认为是一个实体.

由于你不希望出现这种行为,你可以修改你的函数,使其在"to"上分裂:

def extract_dates_with_year(text):
    doc = nlp(text)
    dates_with_year = []
    for ent in doc.ents:
        if ent.label_ == "DATE":
            for ent_txt in ent.text.split("to"):
                dates_with_year.append(ent_txt.strip())
    return dates_with_year

这将正确地处理以下日期,以及单个日期和具有多个日期的字符串:

txt = """
     The dates are from 30 June 2019 to 1 January 2022 inclusive.
     And oddly also 5 January 2024.
     And exclude 21 July 2019 until 23 July 2019.
"""

extract_dates_with_year(txt)

# Output:
[
 '30 June 2019',
 '1 January 2022',
 '5 January 2024',
 '21 July 2019',
 '23 July 2019'
]

Python相关问答推荐

返回nxon矩阵的diag元素,而不使用for循环

三个给定的坐标可以是矩形的点吗

Python在tuple上操作不会通过整个单词匹配

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

如何检测背景有噪的图像中的正方形

在极性中创建条件累积和

在pandas中使用group_by,但有条件

计算分布的标准差

使用Python从URL下载Excel文件

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

Python全局变量递归得到不同的结果

如何使用使用来自其他列的值的公式更新一个rabrame列?

在Admin中显示从ManyToMany通过模型的筛选结果

具有相同图例 colored颜色 和标签的堆叠子图

替换现有列名中的字符,而不创建新列

如何在Python中从html页面中提取html链接?

有了Gekko,可以创建子模型或将模型合并在一起吗?

查找查找表中存在的列值组合

TypeError:';Locator';对象无法在PlayWriter中使用.first()调用

按条件计算将记录拆分成两条记录