Mrye Mrye - 1 year ago 118
Java Question

Find and replace text iteratively from a list

Suppose I have these text :

Donec sollicitudin ? malesuada. "Curabitur" arcu erat, accumsan
id imperdiet et, porttitor at sem. Quisque velit nisi, ? ut
lacinia in, ? id enim. Proin eget tortor risus.


and I have these texts in list :

["apple", "banana", "cherry"]


How can I replace each occurence of ? with each of the text in the list ? Expected output :

Donec sollicitudin apple malesuada. "Curabitur" arcu erat, accumsan
id imperdiet et, porttitor at sem. Quisque velit nisi, banana ut
lacinia in, cherry id enim. Proin eget tortor risus.


Is it possible to use notepad++ to achieve something like this for a longer text and list? Or is there any other technologies that I can use ?

Answer Source

This Python script will get the job done. If there are more ? than replacements in the list, it will leave them as ?.

import re

replacements = ["apple", "banana", "cherry"]
lines = ""

with open("file.txt") as file:
    lines = file.read()

def replace(m):
    if not replacements:
        return "?"

    return replacements.pop(0)

lines = re.sub(r"\?", replace, lines)

with open("file.txt", "w") as file:
    file.write(lines)

Admittedly, there are better ways of doing this, such as not loading the entire file into a string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download