从tex中的单词索引中获取字符索引

2024-06-09 07:04:05 发布

您现在位置:Python中文网/ 问答频道 /正文

给定文本中单词的索引,我需要得到字符索引。 例如,在下面的文本中:

"The cat called other cats."

“猫”这个词的索引是1。 我需要cat的第一个字符的索引,它是4。 我不知道这是否相关,但我使用pythonltk来获取单词。 现在我唯一能想到的办法是:

^{pr2}$

但这将是非常低效的。 任何想法都将得到赞赏。在


Tags: the文本字符单词catothercats办法
3条回答
import re
def char_index(sentence, word_index):
    sentence = re.split('(\s)',sentence) #Parentheses keep split characters
    return len(''.join(sentence[:word_index*2]))

^{pr2}$

使用enumerate()

>>> def obt(phrase, indx):
...     word = phrase.split()[indx]
...     e = list(enumerate(phrase))
...     for i, j in e:
...             if j == word[0] and ''.join(x for y, x in e[i:i+len(word)]) == word:
...                     return i
... 
>>> obt("The cat called other cats.", 1)
4

您可以在此处使用dict

>>> import re
>>> r = re.compile(r'\w+')
>>> text = "The cat called other cats."
>>> dic = { i :(m.start(0), m.group(0)) for i, m in enumerate(r.finditer(text))}
>>> dic
{0: (0, 'The'), 1: (4, 'cat'), 2: (8, 'called'), 3: (15, 'other'), 4: (21, 'cats')}
def char_index(char, word_ind):
    start, word = dic[word_ind]
    ind = word.find(char)
    if ind != -1:
        return start + ind
...     
>>> char_index('c',1)
4
>>> char_index('c',2)
8
>>> char_index('c',3)
>>> char_index('c',4)
21

相关问题 更多 >