gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:16:00 26 4
gpt4 key购买 nike

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

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

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

最佳答案

你也可以这样做:

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)

关于python - 从 nltk word_tokenize 获取原始文本的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31668493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com