替换 Python 中 docx 字符串中的数字

Replace numbers from a docx string in Python

所以我已经使用 docx-python 玩了一段时间,但想不出一种方法来替换字符串中的数字。 我有一段是这样的:NR 050 / 04.10.2019 我确实设法将数字分开,将它们放在列表中并根据需要进行修改。如何将修改后的值放回到 docx 文件的段落中? 到目前为止,这是我的代码:

document = Document('1.docx')

section = document.sections[0]
header = section.header
order = []
for paragraph in header.paragraphs:
    print(paragraph.text)

    for s in re.findall(r'\b\d+\b', paragraph.text):
        int(s)
        order.append(int(s))

print('Contract number:',order[0],'\nContract Date: ',order[1],order[2],order[3])
order[0] = order[0] + 1
print('New contract number: ',order[0])


today = date.today()
day = today.strftime("%d/%m/%Y")
data_curenta = []
for s in re.findall(r'\b\d+\b', day):
    int(s)
    data_curenta.append(int(s))

print('Current date: ',data_curenta[0],data_curenta[1],data_curenta[2])

order[1] = data_curenta[0]
order[2] = data_curenta[1]
order[3] = data_curenta[2]
print('New contract date: ',order[1],order[2],order[3])


将字符串转换为数字的简单方法是将其转换为 int,如果数字是浮点数,试试这个

 num=" 44.545"
 print(int(float(num)))

输出

44

使用 split 分隔列表中的字符串:your_text_var.split("eg. your seprator")

 txt="123.45.67"
 newvar= txt.split(".")
print(newvar)

输出

['123', '45', '67']