Home > Software design >  alternating find replace words python
alternating find replace words python

Time:11-17

Here is the code I have so far

replace_listA = {'Bear': [Black, Woods], 'Duck': [Bird, Feathers]}
replace_listB = {'Bear': [Grizzly, Woods], 'Duck': [Quack, Feathers]}
replace_listC = {'Bear': [Grizzly, Black], 'Duck': [Quack, Bird]}

with open("main.txt") as main:
    words = main.read().split()
replaced = []
for y in words:
    replacement = replace_listA.get(y, y)
    replaced.append(replacement)
text = ' '.join(replaced)
print (text)
new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()

Two things I need to get working is that for each time the word Bear or Duck appears I would like the code to use the first value and then remove it from the list. so taking replace_listA as an example the first instance of the word Bear is replaced with the word "Black" and the second instance is replaced with the word "Woods".

That is the first thing,

The second thing is to then rotate between the 3 replace lists when both values have been used for either Bear of Duck and a new value is needed, (Both values have been used for "Bear" and the word Bear has come up again)

So a list of words

Duck Bear Bear Duck Duck Bear Bear Bear Bear Duck Bear Bear Duck Duck Bear Bear Bear

would become

Bird Black Woods Feathers Quack Grizzly Woods Grizzly Black Quack Black Woods Bird Feathers

because each list would in turn replace

replace_listA
Duck Bear  Bear  Duck 
Bird Black Woods Feathers

replace_listB
Duck  Bear    Bear
Quack Grizzly Woods

replace_listC
Bear    Bear  Duck
Grizzly Black Quack

replace_listA
Bear  Bear  Duck Duck
Black Woods Bird Feathers

CodePudding user response:

I suggest you use a list of dictionaries, this list will be the successive replacements you'll do, you can cycle through this list:

words_input = "Duck Bear Bear Duck Duck Bear Bear Bear Bear Duck Bear Bear Duck Duck"

replacements = [{'Bear': ["Black", "Woods"], 'Duck': ["Bird", "Feathers"]},
                {'Bear': ["Grizzly", "Woods"], 'Duck': ["Quack", "Feathers"]},
                {'Bear': ["Grizzly", "Black"], 'Duck': ["Quack", "Bird"]}]

output = []
index_replace = 0
count_replace = {key: 0 for key in replacements[0].keys()}
for word in words_input.split():
    if count_replace[word] == len(replacements[index_replace][word]):
        # We need to cycle through the replacements
        index_replace = (index_replace   1) % len(replacements)
        count_replace = {key: 0 for key in replacements[0].keys()}
    idx_word = count_replace[word]
    output.append(replacements[index_replace][word][idx_word])
    count_replace[word]  = 1

output_words = ' '.join(output)
print(output_words)
# Bird Black Woods Feathers Quack Grizzly Woods Grizzly Black Quack Black Woods Bird Feathers

(Beware, your example seems not totally accurate, since the last "Bear Bear Bear" are not translated in your original post)

  • Related