从nltk word_tokenize

时间:2015-07-28 06:05:05

标签: python text nltk tokenize

我使用nltk.word_tokenize对文本进行标记,我还希望将原始原始文本中的索引转换为每个标记的第一个字符,即

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

如何获取与标记的原始索引相对应的数组[0, 7]

3 个答案:

答案 0 :(得分:11)

你也可以这样做:

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)

答案 1 :(得分:8)

我认为您正在寻找的是span_tokenize()方法。 Apparently默认令牌化程序不支持此功能。 这是一个带有另一个标记化器的代码示例。

from nltk.tokenize import WhitespaceTokenizer
s = "Good muffins cost $3.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]

有关详细信息(有关可用的不同标记器),请参阅tokenize api docs

答案 2 :(得分:0)

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