>>> 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
>>> 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
^{pr2}$
使用
enumerate()
您可以在此处使用
dict
:相关问题 更多 >
编程相关推荐