python读取docx文件,并进行一些操作

本文介绍如何使用Python的python-docx包读取DOCX文件,并提供了一个示例程序,该程序能够读取指定目录下的所有DOCX文件,移除其中的中文内容后保存回原文件。

python读取docx文件

1、安装包:

先前试用过很多包,都不管用,读取文件时候会出现如下错误:

pywintypes.com_error: (-2147352567, '发生意外。', (0, 'Kingsoft WPS', '文档保存失败。', '', 3011, -2147467259), None)

最后改成docx包,其安装的module为:

pip install python-docx

2、进行读取一个docx文件

其中一定要docx文件,如果是doc文件进行改后缀成docx是会有问题的,导致读取的文件一直是空的,需要原生态就是使用docx创建的文件。

import re,os
from docx import Document

def remove_chinese_line(doc):
    for paragraph in doc.paragraphs:
        temp=paragraph.text
        #判断是否是中文
        cls_idx=re.sub('[\u4e00-\u9fa5]', '', temp)
        print(cls_idx)
        #进行删除对应的段落
        if cls_idx!=temp:
            p=paragraph._element
            p.getparent().remove(p)
            p._p=p._element=None
    return doc

if __name__ == '__main__':
    root="temp/input"
    input_files= os.listdir(root)
    for item in input_files:
        cur_file=os.path.join(root,item)
        document = Document(cur_file)
        doc=remove_chinese_line(document)
        doc.save(cur_file)

其是读取某个目录下的所有docx文件,去除中文后,然后进行保存到源文件。

Python中,你可以使用`python-docx`库来读取`.docx`文件的内容,然后使用加密库如`cryptography`来对文件内容进行加密。以下是一个简单的步骤说明: 首先,你需要安装所需的库: ```bash pip install python-docx cryptography ``` 然后,你可以按照以下代码示例来操作: 1. **读取.docx文件内容**: ```python from docx import Document def read_docx(file_path): doc = Document(file_path) content = '' for paragraph in doc.paragraphs: content += paragraph.text + '\n' return content # 使用函数读取文件内容 content = read_docx('your_file.docx') ``` 2. **选择加密算法和模式**: ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend backend = default_backend() key = b'some_secret_key' # 替换为你想要使用的密钥 cipher_suite = algorithms.AES(key) # AES 加密示例 iv = b'some_initialization_vector' # 初始化向量,也可以随机生成 # 创建一个新的Cipher对象 cipher = Cipher(cipher_suite, modes.CBC(iv), backend=backend) ``` 3. **将内容加密**: ```python def encrypt_content(content, key, iv): encryptor = cipher.encryptor() encrypted_content = encryptor.update(content.encode()) + encryptor.finalize() return (iv, encrypted_content) iv, encrypted_data = encrypt_content(content, key, iv) ``` 4. **保存加密后的数据**: ```python with open('encrypted_content.txt', 'wb') as f: f.write(iv) f.write(encrypted_data) ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值