【问题标题】:How the get the indices of the sents's beginning and ending in spacy?如何获得发送的开始和结束的索引?
【发布时间】:2020-10-05 05:37:47
【问题描述】:

我是使用 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 是否会忽略上面提到的任何其他字符以包含在发送中?

有更好的方法吗?

【问题讨论】:

    标签: python nlp spacy


    【解决方案1】:

    您可以只使用start_charend_char

    for sent in doc.sents:
        print(sent.start_char,sent.end_char) 
    

    一个句子是 spaCy 中的一个 Span,并带有许多有用的属性,这些属性在 docs 中有介绍。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2018-09-29
      • 2012-04-11
      • 1970-01-01
      • 2013-12-11
      相关资源
      最近更新 更多