python - 如何获得发送的开始和结束的索引?
问题描述
我是使用 spacy 的新手。我有一个场景,我必须获取句子在句子中开始和结束的索引。如果我使用文档。发送然后我得到一个发送列表。sent.beg 和 sent.end 打印令牌索引,但我想要字符索引。
for sent in doc.sents:
print(sent.start,sent.end) #prints token index
例子:
completeText = "Hi, I am using StackOverflow. The community is great."
nlp = spacy.load('en_core_web_sm')
nlp.add_pipe(nlp.create_pipe('sentencizer'))
doc = nlp(completeText)
for sent in doc.sents:
print(sent.start,sent.end) #prints 0,7 and 7,12 the token indices
上面的打印语句只打印标记索引,而不是字符索引。我想要的输出是 0,29 和 30, 54。
我试过得到如下句子的长度。我在最后添加了一个 if 语句,因为句号后的空格在句子中被忽略了。
start = [0] * len(list(doc.sents))
end = [0] * len(list(doc.sents))
for index, i in enumerate(doc.sents):
if index !=0:
start[index] = end[index-1] + 1
length += len(str(i))
if index == 0:
end[index] = length
else:
end[index] = length
if end[index] + 1 < len(sent) and sent[end[index]+1] == " ":
length += 1
当句号后只有空格时,这很好用。但是在我拥有的完整文本中(超过 10,000 行),我没有得到正确的答案。spacy 是否会忽略上面提到的任何其他字符以包含在发送中?
有一个更好的方法吗?
解决方案
你可以只使用start_char
and end_char
。
for sent in doc.sents:
print(sent.start_char,sent.end_char)
一个句子是 spaCy 中的一个 Span,并带有许多有用的属性,这些属性在docs中有介绍。
推荐阅读
- angular - Angular 5 应用程序在多个选项卡中打开时冻结 - chrome
- java - 文档的路径对 Firestore 自动生成的随机 ID 有影响吗?
- ios - 为 iOS 创建 Card Connect SDK Xamarin 绑定库的问题
- c# - ASP.NET MVC:如何将当前记录的 StartDate 放在较早记录的 EndDate
- python - 操作顺序和/或
- swift - 调用事件函数时的 CoreWLAN CWEventDelegate EXC_BAD_ACCESS
- python - 如何设置python扩展开发环境?
- google-cloud-platform - 用于插入特定 BigQuery 数据集的 IAM 自定义角色
- django - Django、CORS、CSRF——我做得对吗?
- mongodb - 查找数组 mongodb 中没有关键字的所有文档