Python 模块 mammoth 怎么转换 docx 文件为 html?

2016-10-29 21:05:59 +08:00
 vtoexsir

mammoth 模块,可以将 docx 文件转为 html,可以清理掉 html 代码中 word 的一些特定格式.也能输出 docx 文件中的图片. 在 windows 的 cmd 下,使用如下命令: mammoth document.docx --output-dir=output-dir 则在 output-dir 目录下,输出 html 文件和图片文件. 如下 Python 代码:

with open("document.docx", "rb") as docx_file:
    result = mammoth.convert_to_html(docx_file)
    html = result.value # The generated HTML
    messages = result.messages```

以上代码会生成 html 代码,并不能将 docx 中的图片保存到一个目录里边;
同时在 html 中,图片会被使用 base64 编码,并且删除了 width 和 height 属性.
我想要的是,将图片保留到一个目录里边;
同时生成的 html 代码里,不要将图片使用 base64 编码,并保持图片的 width 和 height 属性.
英文太差,看得头痛也没有搞清楚怎么弄,请大家帮助,最好贴下简单的代码,多谢您的回复!
3691 次点击
所在节点    Python
4 条回复
yexiaoxing
2016-10-29 21:53:27 +08:00
By default, images are included inline in the output HTML. If an output directory is specified by --output-dir, the images are written to separate files instead. For instance:

'mammoth document.docx --output-dir=output-dir'
vtoexsir
2016-10-29 22:12:11 +08:00
@yexiaoxing 感谢您的回复,如上代码在 cmd 执行,在 output-dir 文件夹会生成 html 文件和图片文件,存在的问题是:
html 文件中图片元素(如:<img src="1.png" />)没有高和宽属性,我希望 html 文件中的图片元素保持高宽属性的值,不要过滤掉.如:<img src="1.png" width="300" height="200" />.
这样的效果,用 python 代码可以实现的吗?怎么写呢?
zhuangzhuang1988
2016-10-29 22:27:25 +08:00
代码不都是开源的么, 写个代码 patch 下生成过程就好了
vtoexsir
2016-10-30 11:32:51 +08:00
@zhuangzhuang1988 太菜了,还没那两下子!@@@

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/316467

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX