How do I exchange the 3 and 5 occurrences of a word in a string

Asked

Viewed 194 times

4

Someone can help me in this, I need to change the 3 and 5 occurrence of a word in a text, I can 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
  • A question wants to change the word when it repeats in the string for the third/fifth time, in the same/only in the place where the right third or fifth occurrence was found?

  • only on the 3 and 5 times, and no other.

2 answers

4


You can do it 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" is repeated 3 times and exchanged in the last (third occurrence) and the word "text" is repeated 5 times, exchanged in the third and fifth occurrence

  • problem solved, I will try to implement it here in my code, thank you :D

  • You’re welcome @Adrianobrito, thank goodness

2

The question was already very good answered by Miguel, follows below an alternative manipulating the indices of the string:

def trocar (texto, substituir, substituto, ocorrencias):
    indice = texto.find(substituir)
    cont = texto.count(substituir)
    ret = texto
    n = 1

    while indice >= 0 and n <= cont:
        if n in ocorrencias:
            ret = ret[:indice] + substituto + ret[len(substituir) + indice:]        
        indice = ret.find(substituir, indice + len(substituto))
        n += 1

    return cont, ret

The function returns a tuple with the number of occurrences of the word in string, and the modified text.

Example of use:

texto = "xxxxxxxxxxxxxxx"
#         ↑  ↑  ↑  ↑  ↑
#         1  2  3  4  5

print(trocar(texto, "xxx", "AAA", [1, 2])) # (5, 'AAAAAAxxxxxxxxx')
print(trocar(texto, "xxx", "BBB", [2, 3])) # (5, 'xxxBBBBBBxxxxxx')
print(trocar(texto, "xxx", "CCC", [3, 4])) # (5, 'xxxxxxCCCCCCxxx')
print(trocar(texto, "xxx", "DDD", [4, 5])) # (5, 'xxxxxxxxxDDDDDD')

See demonstração

In your case, you can call her that:

texto = input("Digite o texto: ")
palavra = input("Digite a palavra: ")

cont, trocado = trocar(texto, palavra, "YYY", [3, 5])
print ("{} aparece {} em {}\n".format(palavra, cont, texto))

print (texto)
print (trocado)

# Exemplo de saída
#   Digite o texto: foo foo foo foo bar foo
#   Digite a palavra: foo
#   foo aparece 5 em foo foo foo foo bar foo

#   foo foo foo foo bar foo
#   foo foo YYY foo bar YYY
  • I managed to implement a much simpler code, with about 5or 6 lines only, and using if and for, tomorrow morning I put here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.