从 nltk word_tokenize 获取原始文本的索引

get indices of original text from nltk word_tokenize

我正在使用 nltk.word_tokenize 对文本进行分词,我还想将原始文本中的索引获取到每个分词的第一个字符,即

import nltk
x = 'hello world'
tokens = nltk.word_tokenize(x)
>>> ['hello', 'world']

我怎样才能得到与令牌的原始索引对应的数组[0, 7]

我想你要找的是span_tokenize()方法。 默认分词器不支持此功能。 这是另一个分词器的代码示例。

from nltk.tokenize import WhitespaceTokenizer
s = "Good muffins cost .88\nin New York."
span_generator = WhitespaceTokenizer().span_tokenize(s)
spans = [span for span in span_generator]
print(spans)

给出:

[(0, 4), (5, 12), (13, 17), (18, 23), (24, 26), (27, 30), (31, 36)]

刚得到偏移量:

offsets = [span[0] for span in spans]
[0, 5, 13, 18, 24, 27, 31]

有关更多信息(关于可用的不同标记器),请参阅标记化 api docs

您也可以这样做:

def spans(txt):
    tokens=nltk.word_tokenize(txt)
    offset = 0
    for token in tokens:
        offset = txt.find(token, offset)
        yield token, offset, offset+len(token)
        offset += len(token)


s = "And now for something completely different and."
for token in spans(s):
    print token
    assert token[0]==s[token[1]:token[2]]

并得到:

('And', 0, 3)
('now', 4, 7)
('for', 8, 11)
('something', 12, 21)
('completely', 22, 32)
('different', 33, 42)
('.', 42, 43)

pytokenizations 有一个有用的函数 get_original_spans 来获取跨度:

# $ pip install pytokenizations
import tokenizations
tokens = ["hello", "world"]
text = "Hello world"
tokenizations.get_original_spans(tokens, text)
>>> [(0,5), (6,11)]

这个函数可以处理嘈杂的文本:

tokens = ["a", "bc"]
original_text = "å\n \tBC"
tokenizations.get_original_spans(tokens, original_text)
>>> [(0,1), (4,6)]

有关其他有用的功能,请参阅 the documentation