You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计doc/docx格式Word文档字符数,修复代码报错及实现批量处理

原代码报错原因

你遇到的AttributeError: 'NoneType' object has no attribute 'Characters'错误,核心原因是word.Documents.Open(r"12a.docx")执行失败返回了空值,常见触发场景:

  • 目标文件12a.docx不在当前运行脚本的工作目录下,路径填写错误
  • 目标文件正被其他程序占用锁定
  • 目标文件损坏,不属于合法的Word格式文件
1. Word文档字符数统计可行方案及支持库
  • pywin32(win32com):调用本地Word程序的COM接口,同时支持.doc和.docx格式,统计结果和Word自带的字符统计功能完全一致,仅支持Windows平台,且需要本地安装Microsoft Office
  • python-docx:纯Python实现的第三方库,无需安装Office,仅支持.docx格式,轻量易部署,跨Windows/Mac/Linux平台使用
  • textract:多格式文本解析封装库,同时支持.doc和.docx格式,统计.doc需要额外安装antiword等依赖,适合跨格式批量处理场景
  • docx2txt:轻量级docx文本提取工具,仅支持.docx格式,调用简单,适合仅需要统计文本字符的场景
2. 批量统计选中Word文档字符数实现

假设你通过GUI对话框拿到的选中文件路径列表为selected_word_files,以下是基于pywin32的可运行实现,兼容.doc/.docx,自带异常处理:

from win32com.client import Dispatch
import os

def count_word_chars(file_path, word_app):
    try:
        # 打开文档时加参数避免弹窗
        doc = word_app.Documents.Open(os.path.abspath(file_path), ReadOnly=True, Visible=False)
        # 统计含空格字符数,如需不含空格可改用 doc.Characters.Count - doc.Spaces.Count
        char_count = doc.Characters.Count
        doc.Close(SaveChanges=False)
        return char_count
    except Exception as e:
        print(f"文件{os.path.basename(file_path)}统计失败:{str(e)}")
        return None

if __name__ == "__main__":
    # 这里替换为你GUI拿到的选中文件路径列表,比如tkinter filedialog返回的列表
    selected_word_files = [r"test1.docx", r"test2.doc"]
    # 全局只初始化一次Word实例,避免重复启动拖慢速度
    word = Dispatch('Word.Application')
    word.Visible = False

    for file in selected_word_files:
        cnt = count_word_chars(file, word)
        if cnt is not None:
            print(f"文件名:{os.path.basename(file)},字符数:{cnt}")
    
    # 一定要退出Word进程,避免后台残留
    word.Quit()

如果你的文件都是.docx格式,可以用无需Office的python-docx版本实现:

from docx import Document
import os

def count_docx_chars(file_path):
    try:
        doc = Document(file_path)
        full_text = []
        for para in doc.paragraphs:
            full_text.append(para.text)
        # 如需统计表格字符可额外遍历doc.tables提取内容
        return len(''.join(full_text))
    except Exception as e:
        print(f"文件{os.path.basename(file_path)}统计失败:{str(e)}")
        return None

# 调用逻辑和上面pywin32版本一致,无需启动Word进程
3. 统计结果存储为变量

直接用字典存储即可,键为文件路径/文件名,值为对应字符数,后续可随时调用:

# 初始化存储字典
result_dict = {}

for file in selected_word_files:
    cnt = count_word_chars(file, word)
    if cnt is not None:
        result_dict[file] = cnt

# 后续使用示例
print(result_dict[r"test1.docx"]) # 直接获取对应文件的字符数

内容的提问来源于stack exchange,提问作者Hacker--Rohan Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:18:05