我有一个文件夹,里面有许多以结尾的word文档文件.文件和.docx.

此代码仅适用于.docx文件

import docx
import os

charCounts = {}
directory = os.fsencode('.')
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".docx"):
        #filename = os.path.join(directory, filename)
        doc = docx.Document(filename)
        chars = sum(len(p.text) for p in doc.paragraphs)
        charCounts[filename] = chars / 65

# uses openpyxl package
from openpyxl import Workbook
wb = Workbook()
ws = wb.active

ws.cell(row=1, column=2, value='File Name')
ws.cell(row=1, column=4, value='chars/65')
for i, x in enumerate(charCounts):
    ws.cell(row=i + 3, column=2, value=x)
    ws.cell(row=i + 3, column=4, value=charCounts[x])
    ws.cell(row=len(charCounts) + 3, column=4, value=sum(charCounts.values()))
path = './charCounts.xlsx'
wb.save(path)

图像:-

I have files like these. enter image description here

我希望它们像这样发生:

enter image description here

注意两件事.

excel表中的文件名已按数字排列.

第二件事是在excel工作表中,文件扩展名已被删除.我想要这样.

推荐答案

以下是您问题中代码的更新,我相信这将满足您的要求:

# uses python-docx package
import docx
import os

# uses pywin32 package
import win32com.client as win32
from win32com.client import constants
app = win32.gencache.EnsureDispatch('Word.Application')

charCounts = {}
fileDir = '.' # Put the path of the directory to be searched here
os.chdir(fileDir)
cwd = os.getcwd()
directory = os.fsencode(cwd)
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.startswith('TEMP_CONVERTED_WORD_FILE_'):
        continue
    filenameOrig = None
    if filename.endswith(".doc"):
        filenameOrig = filename
        src_path = os.path.join(cwd, filename)
        src_path_norm = os.path.normpath(src_path)
        doc = app.Documents.Open(src_path_norm)
        doc.Activate()
        docxPath = 'TEMP_CONVERTED_WORD_FILE_' + filename[:-4] + ".docx"
        dest_path = os.path.join(cwd, docxPath)
        dest_path_norm = os.path.normpath(dest_path)
        app.ActiveDocument.SaveAs(dest_path_norm, FileFormat=constants.wdFormatXMLDocument)
        doc.Close(False)
        filename = docxPath
    if filename.endswith(".docx"):
        src_path = os.path.join(cwd, filename)
        src_path_norm = os.path.normpath(src_path)
        doc = docx.Document(src_path_norm)
        chars = sum(len(p.text) for p in doc.paragraphs) + sum(len(p.text) for section in doc.sections for hf in [section.header, section.footer] for p in hf.paragraphs)
        charCounts[filenameOrig if filenameOrig else filename] = chars / 65
charCounts = {k:charCounts[k] for k in sorted(charCounts)}

# uses openpyxl package
from openpyxl import Workbook
wb = Workbook()
ws = wb.active

ws.cell(row=1, column=2, value='File Name')
ws.cell(row=1, column=4, value='chars/65')
for i, x in enumerate(charCounts):
    ws.cell(row=i + 3, column=2, value=x[:-4] if x.endswith('.doc') else x[:-5])
    ws.cell(row=i + 3, column=4, value=charCounts[x])
ws.cell(row=len(charCounts) + 3, column=3, value='Total')
ws.cell(row=len(charCounts) + 3, column=4, value=sum(charCounts.values()))
path = './charCounts.xlsx'
wb.save(path)

说明:

  • 对于名称以.docx结尾的每个文件(以TEMP_CONVERTED_WORD_FILE_开头的文件除外),将字符数(除以65)除以文件名作为键存储在字典charCount
  • 对于每个以.doc结尾的文件,使用Win32 extensions的pywin32包将其转换为.docx文件,文件名前加TEMP_CONVERTED_WORD_FILE_,然后将字符数(除以65)与其原始文件名作为键存储在上述同一字典中
  • charCounts字典替换为按文件名键具有插入顺序的字典
  • 遍历charCounts将内容存储在Excel文件中,注意截断文件名键的.doc.docx后缀.

Python相关问答推荐

如何创建引用列表并分配值的Systemrame列

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

以异步方式填充Pandas 数据帧

判断Python操作:如何从字面上得到所有decorator ?

在电影中向西北方向对齐""

如何强制向量中的特定元素在Gekko中处于优化解决方案中

Polars表达式无法访问中间列创建表达式

VSCode Pylance假阳性(?)对ImportError的react

为什么fizzbuzz在两个数字的条件出现在一个数字的条件之后时不起作用?

排除NRRD文件中的多切片卷加载问题

为什么REGISTER_NEXT_STEP_HANDLER不立即调用函数并等待另一条消息

编撰词典的功能

新进程不会在运行FastApi的Docker中启动

极点中的链接表达式不起作用

如何在Python中以一种安全的方式获取Git提交散列

是否有与字节文字等价的函数?

Django-自动完成搜索为已注销用户抛出错误?

游程编码产生错误的结果

如何在多维情况下检验NumPy数组切片是否为副本?

用于具有多个输出的函数的JAX`Custom_vjp`