import os
import win32com.client
def extract_text_from_word_files(folder_path):
# Wordアプリケーションを起動
word_app = win32com.client.Dispatch("Word.Application")
word_app.Visible = False
# フォルダ内のすべてのファイルをチェック
for filename in os.listdir(folder_path):
if filename.endswith(".docx") or filename.endswith(".doc"):
word_file_path = os.path.join(folder_path, filename)
output_txt_file_path = os.path.join(folder_path, filename.rsplit('.', 1)[0] + '_output.txt')
# Wordファイルを開く
doc = word_app.Documents.Open(word_file_path)
# ドキュメント内のすべてのテキストを取得
full_text = doc.Range().Text
# Wordファイルを閉じる
doc.Close()
# テキストをtxtファイルに書き出す
with open(output_txt_file_path, 'w', encoding='utf-8') as txt_file:
txt_file.write(full_text)
# Wordアプリケーションを終了
word_app.Quit()
# 使用例
folder_path = "path_to_your_folder" # Wordファイルが保存されているフォルダのパス
extract_text_from_word_files(folder_path)
表を別にしたいなぁ
import os
import win32com.client
def extract_text_from_word_files(folder_path):
# Wordアプリケーションを起動
word_app = win32com.client.Dispatch("Word.Application")
word_app.Visible = False
# フォルダ内のすべてのファイルをチェック
for filename in os.listdir(folder_path):
if filename.endswith(".docx") or filename.endswith(".doc"):
word_file_path = os.path.join(folder_path, filename)
output_txt_file_path = os.path.join(folder_path, filename.rsplit('.', 1)[0] + '_output.txt')
# Wordファイルを開く
doc = word_app.Documents.Open(word_file_path)
# ドキュメント内のすべてのテキストを取得
full_text = doc.Range().Text
# 表の内容を個別に取得
table_text = ""
for table in doc.Tables:
for row in table.Rows:
row_text = "\t".join([cell.Range.Text.strip('\r\x07') for cell in row.Cells])
table_text += row_text + "\n"
# Wordファイルを閉じる
doc.Close()
# テキストをtxtファイルに書き出す
with open(output_txt_file_path, 'w', encoding='utf-8') as txt_file:
txt_file.write(full_text)
txt_file.write("\n\n--- Tables ---\n\n")
txt_file.write(table_text)
# Wordアプリケーションを終了
word_app.Quit()
# 使用例
folder_path = "path_to_your_folder" # Wordファイルが保存されているフォルダのパス
extract_text_from_word_files(folder_path)