Jun-18-2022, 08:24 AM
I'm working on a personal project where I can change any word I can find in the text:
How can I match the position of words with the NumberList given in the function?,
so I can output new text like this (you -> Cleis):
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)
for p in doc.paragraphs:
inline = p.runs
match = re.finditer(key,p.text,re.IGNORECASE) #find key
for igkey in match:
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)
path = r'path of file'
replace(path,'you','Cleis',[2,5,8],'test2.docx')I tried it on a file containing the following text:Quote:Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years. Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years. Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years.
How can I match the position of words with the NumberList given in the function?,
so I can output new text like this (you -> Cleis):
Quote:Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope you stay lonely and live for a hundred years. Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope you stay lonely and live for a hundred years. Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope you stay lonely and live for a hundred years.
