2017-09-14 2 views
0

j'écrire ce code en pythoncomment trouver l'index de mot dupliquée en python

import re 

text = input('please enter text: ') 
word = re.findall('\w+', text) 
len_word = len(word) 
word_pos = [] 

for i 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) 

et la sortie de cette entrée: aa, est: [0, 2], et est correcte, mais ce siguation: aaa, réponse est: [0, 2, 1], je veux voir: [0, 2, 4], et je veux un code dynamique parce que je ne sais pas quand je reçois le mot de duplacated contribution. et s'il y a une solution que je veux obtenir l'index de texte plus dupliquée grâce

+0

Quelle est entrée exacte? –

+0

Ow, ma complexité algorithmique! Trouver un moyen d'éviter cette recherche linéaire. – o11c

+0

Est-il nécessaire que l'entrée soit une chaîne? Si la chaîne est 'split()' dans une liste de mots, les indices des réplicats sont différents. Exemple: '" a a a ".split()' -> '['a', 'a', 'a']' -> '[0, 1, 2]' à la place. De plus, les mots répétés sont différents des lettres répétées. Qu'est-ce que vous attendez de '" foo bar aaaa aaa bar "'? – pylang

Répondre

2

Vous pouvez faire quelque chose comme ça:

import re 

text = input('please enter text: ') 
words = re.findall('\w+', text) 
word_pos = [] 
pos = 0 # this will help us track the word's position in the original text 

for i in range(len(words)): 
    word = words[i] 
    pos += text[pos:].index(word) # we use the position of the last word to find the position of the current word 
    if word in words[i+1:] or word in words[:i]: # we have a duplicate so we can append this position 
     word_pos.append(pos) 
     print('{} found at {} in text'.format(word,pos)) 
    pos += 1 

Avec entrée: "a a a a", je reçois le résultat:

please enter text: a a a a a 
a found at 0 in text 
a found at 2 in text 
a found at 4 in text 
a found at 6 in text 
a found at 8 in text 
+0

Je viens de le faire, désolé pour le retard. Pourquoi la downvote si? Nom – Flynsee

+0

« de word_pos » est pas défini – Arun

+0

@Arun Mon mauvais, il était dans le code de l'OP. Je viens de l'ajouter. – Flynsee

0
import re 
text = input('please enter text: ') 
print({word: [w.start() for w in re.finditer(word, text)] for word in text.split()}) 

entrée 1:

please enter text: a a a a 

output: 
{'a': [0, 2, 4, 6]} 

input 2: 
please enter text: Hello Arun Hello man 

output: 
{'Arun': [6], 'Hello': [0, 11], 'man': [17]}