使用 spaCy 进行 Span 相似度计算
确定语义相似度有助于将文本归入预定义类别、检测相关文本,或标记重复内容。在本练习中,您将练习计算文档中多个片段与给定文档的语义相似度。目标是找到与 canned dog food 最相关的、由 3 个词元组成的 Span。
给定的 canned dog food 类别已存储在 category 中。文本字符串已存储在 text 对象中,并且 en_core_web_md 已以 nlp 名称加载。text 的 Doc 容器也已创建并存储在 document 中。
本练习是课程的一部分
使用 spaCy 的自然语言处理
练习说明
- 为
category创建一个Doc容器,并存储为category_document。 - 打印给定
Span与category_document的相似度分数,并四舍五入到小数点后三位。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a Doc container for the category
category = "canned dog food"
category_document = nlp(____)
# Print similarity score of a given Span and category_document
document_span = document[0:3]
print(f"Semantic similarity with", document_span.text, ":", round(document_span.____(____), 3))