indexing - how to find index of duplicated word in python -
i write code in python
import re text = input('please enter text: ') word = re.findall('\w+', text) len_word = len(word) word_pos = [] in range(len_word): if text.index(word[i]) in word_pos: prev_index = text.index(word[i]) + 1 last_index = 0 # print('index1: ' , last_index) text = text[prev_index:] # print('new_text: ' , new_text) word_pos.append(text.index(word[i]) + prev_index + last_index) last_index += prev_index else: word_pos.append(text.index(word[i])) print(word_pos)
and output of input: a , is: [0 , 2] , , correct , in siguation: a , answer : [0 , 2 , 1] , want see : [0 , 2 , 4] , , want dynamic code because don't know when duplacated word input. , if there solution want more duplicated word index thanks
you can that:
import re text = input('please enter text: ') words = re.findall('\w+', text) word_pos = [] pos = 0 # track word's position in original text in range(len(words)): word = words[i] pos += text[pos:].index(word) # use position of last word find position of current word if word in words[i+1:] or word in words[:i]: # have duplicate can append position word_pos.append(pos) print('{} found @ {} in text'.format(word,pos)) pos += 1
with input: "a a a"
, result:
please enter text: a a a found @ 0 in text found @ 2 in text found @ 4 in text found @ 6 in text found @ 8 in text
Comments
Post a Comment