.m 文件不包含颜色信息。这是由您使用的任何 IDE/编辑器添加的。
如果您知道(或可以找到)如何将 html 格式或 rtf 格式的文本插入到您的 word 文档中,请查看pygments 模块。
我不确定如何将这种 rtf 格式的文本写入 word 文档。但是,如果您将其写入 RTF 文档,则可以通过 Word 将其打开并保存。
假设我运行这段代码toword.py:
from docx import Document
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import RtfFormatter
with open("toword.py", "r") as f:
code = f.read()
ht = highlight(code, PythonLexer(), RtfFormatter())
with open("rtffile.rtf", "w") as wf:
wf.write(ht)
doc = Document()
paragraph = doc.add_paragraph(ht)
doc.save("code.docx")
还有一个pygments.lexers.matlab.MatlabLexer 格式的 Matlab 文件。或者您可以使用 pygments.lexers.get_lexer_for_filename(filename) 从文件名中获取词法分析器。
在 Word 中打开 rtffile.rtf:
在 Word 中打开code.docx:
或者,您可以使用pandoc 模块及其backend。如果你提供一些markdown,它可以转换为docx格式,如果markdown包含代码围栏,它可以自动突出显示。
所以用这段代码:
# from docx import Document
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import pandoc
with open("toword.py", "r") as f:
code = f.read()
md = f"`````python\n{code}\n`````";
doc = pandoc.Document()
doc.markdown = bytearray(md, encoding="utf-8")
doc.add_argument("out=code.docx")
doc.docx
我们得到以下code.docx:
您可以使用--highlight-style=... 参数来使用突出显示样式。更多信息here