zoukankan      html  css  js  c++  java
  • python 好久不用,基础重拾系列(1,读取word(.doc&&.docx)2,批量转换.doc为.docx后缀 3,相对地址转绝对地址)

    直接给代码,因为注释已经很详细了。

     1 #读取docx中的文本代码示例
     2 import docx
     3 import os
     4 from win32com import client as wc
     5 #将doc转成docx
     6 def doSaveAas(doc_path,docx_path):
     7     word = wc.Dispatch('Word.Application')
     8     doc = word.Documents.Open(doc_path)  # 目标路径下的文件
     9     doc.SaveAs(docx_path, 12, False, "", True, "", False, False, False, False)  # 转化后路径下的文件
    10     doc.Close()
    11     word.Quit()
    12 
    13 #将相对路径转换乘绝对路径,同时调用转换文件进行转换,同时再顺便删除之前的文件
    14 def Dir_doc2docx(Dir_path):
    15     for file_name in os.listdir(Dir_path):
    16         print("AAAAAAAAAAAAAAAA")
    17         print("文件名:"+file_name)
    18         file_path = os.path.join(Dir_path, file_name)
    19         print("文件后缀:"+os.path.splitext(file_name)[1] )
    20         if os.path.splitext(file_name)[1] == '.doc':
    21             abs_file_path=os.path.abspath(file_path)
    22             print("绝对路径:"+abs_file_path)
    23             doSaveAas(abs_file_path,abs_file_path+'x')
    24         try:
    25             os.remove(file_path)
    26         except:
    27             continue
    28 
    29 if __name__ =="__main__":
    30     #获取文档对象
    31     Dir_path="..data"
    32     Dir_doc2docx(Dir_path)
    33     file_name=os.listdir(Dir_path)[1]
    34     file_path = os.path.join(Dir_path, file_name)
    35     print(file_path)
    36     file=docx.Document(file_path)
    37     print("段落数:"+str(len(file.paragraphs)))#段落数为13,每个回车隔离一段
    38     #输出每一段的内容
    39     for para in file.paragraphs:
    40         print(para.text)
    41     #输出段落编号及段落内容
    42     for i in range(len(file.paragraphs)):
    43         print(""+str(i)+"段的内容是:"+file.paragraphs[i].text)
  • 相关阅读:
    Ubuntu 14 如何解压 .zip、.rar 文件
    python 自定义异常
    python 简单的自定义异常类模版
    python 获取文件目录位置
    python获取当前文件路径以及父文件路径
    python tar 打包
    python requests 上传文件
    android:ems="10"是什么意思
    django 应用中获取访问者ip地址
    curl: (6) Could not resolve host: www.baidu.com;
  • 原文地址:https://www.cnblogs.com/smartisn/p/13887592.html
Copyright © 2011-2022 走看看