新手求助:如何在Google Colab中导入Google Drive的Word文档为文本文件
在Google Colab中将Google Drive的Word文档转为文本文件
步骤1:安装处理Word文档的依赖库
在Colab单元格中执行以下命令安装python-docx库:
!pip install python-docx
步骤2:选择适合的方法提取文本
方法一:通过已挂载的Drive路径读取(推荐,若知道文件具体路径)
from docx import Document # 替换为你的Word文档在Drive中的实际路径,比如"/content/drive/MyDrive/文档/我的文件.docx" doc_path = "/content/drive/MyDrive/你的Word文档路径.docx" # 读取文档 doc = Document(doc_path) # 提取所有段落文本 full_text = "\n".join([para.text for para in doc.paragraphs]) # 保存为文本文件到Drive,替换为你想要的输出路径 output_path = "/content/drive/MyDrive/输出的文本文件.txt" with open(output_path, "w", encoding="utf-8") as f: f.write(full_text) print("文本提取完成,文件已保存到指定路径!")
方法二:通过文件ID读取(若不清楚文件路径)
from docx import Document import os from google.colab import drive # 确保Drive已挂载(若之前已挂载可跳过此行) drive.mount('/content/drive') # 替换为你的Word文档的文件ID file_id = "你的文件ID" # 下载文件到Colab临时目录 !gdown --id {file_id} -O temp_doc.docx # 读取文档并提取文本 doc = Document("temp_doc.docx") full_text = "\n".join([para.text for para in doc.paragraphs]) # 保存文本到Drive output_path = "/content/drive/MyDrive/输出的文本文件.txt" with open(output_path, "w", encoding="utf-8") as f: f.write(full_text) # 清理临时文件 os.remove("temp_doc.docx") print("文本提取完成,文件已保存到Drive!")
额外处理:提取表格内容(可选)
如果你的Word文档包含表格,可添加以下代码提取表格内容并合并到文本中:
# 在提取段落文本后添加这段代码 table_content = [] for table in doc.tables: for row in table.rows: # 用制表符分隔单元格内容 row_text = "\t".join([cell.text for cell in row.cells]) table_content.append(row_text) # 将表格内容合并到总文本 full_text += "\n\n--- 表格内容 ---\n" + "\n".join(table_content)
内容的提问来源于stack exchange,提问作者Odiaka Olika
相关产品推荐
相关产品推荐

