Home > Net >  python replace and cycle dictionary values for each occurance of key
python replace and cycle dictionary values for each occurance of key

Time:11-18

Does anybody know how to modify this script so that it iterates through the key values each time it finds a specific word

word_replacement = {'rat':['pat', 'grey', 'squeeky']}

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:

rat went to the rat park to play with rat friends at the rat party

desired output:

pat went to the grey park to play with squeeky friends at the pat party

CodePudding user response:

When you get a dictionary entry for a given word, you need to process its value as a list and pick one of the items in that list as the substitute for the original word (instead of appending the whole list). Each time you use an item in the list, you should move it to the end so that the next occurrence of the keyword uses a different replacement word:

word_replacement = {'rat':['pat', 'grey', 'squeeky']}

words = "rat went to the rat park to play with rat friends at the rat party".split()
replaced = []
for y in words:
    replacements = word_replacement.get(y) # get replacement list
    if replacements:                       # if there is one, change y
        y = replacements.pop(0)            # use first replacement word
        replacements.append(y)             # and move it to the end of the list
    replaced.append(y)                     # add original or replaced word
text = ' '.join(replaced)


print (text)
pat went to the grey park to play with squeeky friends at the pat party

CodePudding user response:

replace_idx = 0
for i, y in enumerate(words):
    if y in word_replacement:
        words[i] = word_replacement[y][replace_idx]
        replace_idx  = (replace_idx    1)%3

text = ' '.join(words)
print(text)

This replaces the words without creating a new list of words. Also, it works with a larger dict of word_replacements.

CodePudding user response:

Easiest way is to have a counter and increment it when you replaced it. I don't know that form of your actual word_replacement dict, but you might want to save multiple counters, each to track a different word.

word_replacement = {'rat':['pat', 'grey', 'squeeky']}

with open("main.txt") as main:
    words = main.read().split()

replaced = []
counter_for_rat = 0 # This is your counter
for y in words:
    n = word_replacement.get(y) # Return None if word not in word_replacement
    if n is not None:
        n = n[counter_for_rat % len(n)] # This prevents index out of range
        counter_for_rat  = 1
    else:
        n = y
    replaced.append(n)
text = ' '.join(replaced)


print (text)

new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()
  • Related