如何在python-docx中同时使用粗体和斜体? [英] How do I apply both bold and italics in python-docx?

查看:103
本文介绍了如何在python-docx中同时使用粗体和斜体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作字典.我正在使用python-docx将其放入MS Word.我可以很容易地将其设置为粗体或斜体,但似乎无法弄清楚如何做到这两种方法.这是基础知识:

I'm working on making a dictionary. I'm using python-docx to put it into MS Word. I can easily make it bold, or italics, but can't seem to figure out how to do both. Here's the basics:

import docx

word = 'Dictionary'

doc = docx.Document()
p = doc.add_paragraph()
p.add_run(word).bold = True

doc.save('test.docx')

我已经尝试过p.add_run(word).bold.italic = True,但是收到一个"NoneType"错误,据我了解.

I have tried p.add_run(word).bold.italic = True, but receive a 'NoneType' error, which I understand.

在add_run之前和之后,我也尝试过p.bold = True和p.italic = True,但是都失去了格式化的能力.

I have also tried p.bold = True and p.italic = True before and after the add_run, but lose formatting all together.

Word的查找/替换是一个简单的解决方案,但如果可以的话,我宁愿在代码中进行.

Word's find/replace is a simple solution, but I'd prefer to do it in the code if I can.

推荐答案

每次调用 add_run 方法都会返回 Run 的新实例.您需要创建一个实例,然后应用 italic bold

The add_run method will return a new instance of Run each time it is called. You need create a single instance and then apply italic and bold

import docx

word = 'Dictionary'

doc = docx.Document()
p = doc.add_paragraph()

runner = p.add_run(word)
runner.bold = True
runner.italic = True

doc.save('test.docx')

这篇关于如何在python-docx中同时使用粗体和斜体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆