Python - 操作 doc / docx

文章目录


注意:doc/docx 文件名中如果包含空格,可能导致读取失败,可以提前替换为 _


读取 docx

textract 和 docx2txt 两个库都支持读取 docx

import textract
import docx2txt

file_path = '.../docx/a.docx'
print('file_path : ', file_path)
bs = textract.process(file_path)  # 得到的是 bytes
text1 = bs.decode('utf-8')

text2 = docx2txt.process(file_path)


读取 doc

安装 antiword
参考:https://blog.csdn.net/Webben/article/details/103343828


def test2():

    root_dir = '../doc/'
    txt_dir = root_dir + 'txt/'

    command_path = '/home/xx/software/antiword-0.37/antiword'

    for file_name in os.listdir(root_dir):

        file_id = file_name.replace('.doc', '')
        print('\n-- ', file_id)

        doc_path = root_dir + file_name
        txt_path = txt_dir + file_id + '.txt'
 
        script = f'{command_path} -f {doc_path} > {txt_path} '
        try:
            ret = os.system(script) 
        except Exception as err:
            print('xx error : ', file_name)
            continue



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值