Question:
Can anyone help me with this, I need to change the 3rd and 5th occurrence of a word in a text, I can't change the other occurrences.
Texto=input("Digite o Texto: ") #recebendo o texto do usuario
Palavra=input("Digite a Palavra: ")#Recebendo a palavra do usuario
cont=Texto.count(Palavra) #atribuindo a cont...
print(cont) #Imprimindo a quantidade de ocorrencias da palavra
Text_Aux=Texto.replace(Palavra, "TROCADO",3)#trocando as 3 primeiras ocorrencias
Texto=Text_Aux# atribuindo a string auxiliar a original
Answer:
You can do like this:
my_str = 'Isto é o meu texto , sim é o meu querido texto , gosto muito deste texto ... Melhor texto do mundo, sim é um texto '
words = my_str.split()
words_count = {}
for k, val in enumerate(words):
words_count[val] = words_count.get(val, 0) + 1 # caso val não haja como chave do dict vamos colocar o valor 0 e somar 1
if words_count[val] == 3:
words[k] = 'YOOOOOO'
elif words_count[val] == 5:
words[k] = 'HEYYYYYYY'
new_str = ' '.join(words)
print(new_str) # Isto é o meu texto , sim é o meu querido texto , gosto muito deste YOOOOOO ... Melhor texto do mundo, sim YOOOOOO um HEYYYYYYY
In this case the word "é" is repeated 3 times and changed on the last (third occurrence) and the word "text" is repeated 5 times, changed on the third and fifth occurrence