Does anybody know how to modify this script so that it switches dictionary for every instance of the word "rat"
word_replacement = [{'dog': 'Bob', 'cat': 'Sally', 'bird': 'John', 'rat': 'Pat'},
{'dog': 'Brown', 'cat': 'White', 'bird': 'Black', 'rat': 'Grey'},
{'dog': 'Bark', 'cat': 'Meow', 'bird': 'Chirp', 'rat': 'Squeek'}]
with open("main.txt") as main:
words = main.read().split()
replaced = []
for y in words:
replacement = word_replacement.get(y, y)
replaced.append(replacement)
text = ' '.join(replaced)
print (text)
new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()
Sample input:
dog bird rat dog cat cat rat bird rat cat dog
desired output:
Bob John Pat Brown White White Grey Chirp Squeek Sally Bob
CodePudding user response:
It has already be pointed out that word_replacement
is a list so you have to access its elements with an index you'll be incrementing when rat
is met:
word_replacement = [{'dog': 'Bob', 'cat': 'Sally', 'bird': 'John', 'rat': 'Pat'},
{'dog': 'Brown', 'cat': 'White', 'bird': 'Black', 'rat': 'Grey'},
{'dog': 'Bark', 'cat': 'Meow', 'bird': 'Chirp', 'rat': 'Squeek'}]
input_str = "dog bird rat dog cat cat rat bird rat cat dog"
words = input_str.split()
replaced = []
dic_list_idx = 0
list_len = len(word_replacement)
for w in words:
replacement = word_replacement[dic_list_idx % list_len].get(w, w)
replaced.append(replacement)
if w == "rat":
dic_list_idx = 1
text = ' '.join(replaced)
print (text)
new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()
dic_list_idx % list_len
allows you to start from the first dictionary when you reach the end of the list.
Output:
Bob John Pat Brown White White Grey Chirp Squeek Sally Bob
Note: in your example it seems there's some confusion between keys and values (shouldn't bird
be replaced with John
?)
CodePudding user response:
There are multiple ways, but 2 come to mind at first:
- Have a counter in loop which you increase whenever you get 'rat', and reset to zero if you reach the end:
i = 0
for y in words.split():
replacement = word_replacement[i][y]
replaced.append(replacement)
if y == 'rat':
i = 1
if i == len(word_replacement):
i = 0
text = ' '.join(replaced)
print(text)
- Always use the first dictionary in the list, but on every occurrence of word 'rat' pop the first dict and push it in the back :D
for y in words.split():
replacement = word_replacement[0][y]
replaced.append(replacement)
if y == 'rat':
word_replacement.append(word_replacement.pop(0))
text = ' '.join(replaced)