[英]Using python RE to replace a string in Word Document?
So i am trying to run through a word document to replace all text strings with 'aaa' (just for example) to replace it with a variable from user input, i have been bashing my head with a few answers on stackoverflow to figure out and came across Regular expressions which i have never used before, after using a tutorial for a bit I just can't seem to get my head round it. 因此,我试图通过一个word文档来替换所有文本字符串,用'aaa'(仅作为例子)将其替换为来自用户输入的变量,我一直在用stackoverflow上的几个答案抨击我的头脑来弄清楚遇到了我之前从未使用过的正则表达式,在使用了一些教程之后我似乎无法理解它。
This is all the code i have tried exampling but just can't seem to get python to actually change the text string in this Word Document. 这是我尝试过的所有代码示例,但似乎无法让python实际更改此Word文档中的文本字符串。
from docx import Document
import re
signature = Document ('test1.docx')
person = raw_input('Name?')
person = person+('.docx')
save = signature.save(person)
name_change = raw_input('Change name?')
line = re.sub('[a]{3}',name_change,signature)
print line
save
for line in signature.paragraphs:
line = re.sub('[a]{3}',name_change,signature)
for table in signature.tables:
for cell in table.cells:
for paragraph in cell.paragraphs:
if 'aaa' in paragraph.text:
print paragraph.text
paragraph.text= replace('aaa',name_change)
save
Thank you in advance for any help. 预先感谢您的任何帮助。
for line in signature.paragraphs:
line = re.sub('[a]{3}',name_change,signature)
The above code is redundant since you update the variable line
with the re.sub, but it doesn't cause an update in the actual origin, as shown below: 上面的代码是多余的,因为您使用re.sub更新变量
line
,但它不会导致实际原点的更新,如下所示:
data = ['aaa', 'baaa']
for item in data:
item = re.sub('[a]{3}', 't', item)
print(data)
#['aaa', 'baaa']
Also, you are iterating over signature.paragraphs
but just calling re.sub
on the entirety of signature
everytime. 此外,您正在迭代
signature.paragraphs
但每次只在整个signature
上调用re.sub
。 Try something like this: 尝试这样的事情:
signature = re.sub('[a]{3}', name_change, signature)
save
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.