Jun-18-2022, 09:03 AM
(This post was last modified: Jun-18-2022, 09:03 AM by Gribouillis.)
def replace(input_file,key,value,Numberlist,output_file): # Input_file: path of file, key: word to change,value: word change,Numberlist: ordinal number of words to change # Output: file save with new file have value doc = Document(input_file) numberset = set(Numberlist) for p in doc.paragraphs: inline = p.runs match = re.finditer(key,p.text,re.IGNORECASE) #find key for n, igkey in enumerate(match, 1): if n not in numberset: continue L_key = igkey.group() for j in range(len(inline)): if L_key in inline[j].text: text = inline[j].text.replace(L_key, value) inline[j].text = text #print(p.text) doc.save(output_file)The effect of enumerate is to iterate on pairs
(1, matchobj), (2, matchobj), (3, matchobj), ...
instead of just match objects. Use the index n to reject occurrences that are not pointed to by Numberlist.Edit: I realize that it will take the same numbers in every paragraph, this may not be what you want...