V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vtoexsir
V2EX  ›  Python

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

  •  
  •   vtoexsir · 2016-10-29 21:05:59 +08:00 · 3683 次点击
    这是一个创建于 2737 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 属性.
    英文太差,看得头痛也没有搞清楚怎么弄,请大家帮助,最好贴下简单的代码,多谢您的回复!
    
    4 条回复    2016-10-30 11:32:51 +08:00
    yexiaoxing
        1
    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
        2
    vtoexsir  
    OP
       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
        3
    zhuangzhuang1988  
       2016-10-29 22:27:25 +08:00
    代码不都是开源的么, 写个代码 patch 下生成过程就好了
    vtoexsir
        4
    vtoexsir  
    OP
       2016-10-30 11:32:51 +08:00
    @zhuangzhuang1988 太菜了,还没那两下子!@@@
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2501 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 00:22 · PVG 08:22 · LAX 17:22 · JFK 20:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.