そのほか
2025/06/04
古川 直輝

Google Colaboratoryを使ってGoogleドキュメントを処理する方法

logo_Python

この記事では、Google Colaboratoryを使ってGoogleドキュメントの内容を自動取得し、そのテキストを.txtファイルに変換・保存する方法をご紹介します。API連携の基本も学べるため、初めてGoogle APIを扱う方にもおすすめです。

はじめに

Googleドキュメントは、オンラインで文書を作成・共有できる便利なサービスです。しかし、自然言語処理やデータ分析を行う際には、Pythonなどのプログラムでその中身を取得して処理したい場面も多くあります。


この記事では、Google Colaboratoryを使ってGoogleドキュメントの内容を自動取得し、そのテキストを.txtファイルに変換・保存する方法をご紹介します。API連携の基本も学べるため、初めてGoogle APIを扱う方にもおすすめです。


実行環境と必要なもの

実行環境


Google Colaboratory


 


使用するAPI



  • Google Drive API

  • Google Docs API


実行手順


  1. Google Drive APIを使用してフォルダーID、ファイルIDの取得

  2. Google Docsを使用してGoogle Documentファイルのテキストを取得

  3. 取得したテキストをテキストファイルに保存


実行コード

必要なライブラリーのインポート



import pandas as pd
import os
import glob
from google.colab import auth
from googleapiclient.discovery import build
import requests
import json
import unicodedata


Google Colabの認証



from google.colab import drive
drive.mount("/content/drive")


Google Cloudの認証



auth.authenticate_user()

drive_service = build('drive', 'v3')
docs_service = build('docs', 'v1')


フォルダIDの取得



path = "/content/drive/MyDrive/test"
files = glob.glob(os.path.join(path,"*.gdoc"))

folder_name = path.split("/")[-1]
query = f"mimeType = 'application/vnd.google-apps.folder' and name = '{folder_name}'"

results = drive_service.files().list(q=query, fields="files(id, name)").execute()
folders = results.get('files', [])
folder_id = folders[0]["id"]


ファイルIDの取得



query = f"'{folder_id}' in parents and mimeType = 'application/vnd.google-apps.document'"
results = drive_service.files().list(q=query, spaces='drive').execute()

dicts = {}
items = results.get('files', [])
for item in items:
normalized_name = unicodedata.normalize('NFKC', item['name']) # 正規化
dicts[normalized_name] = item['id']

file_id = []
file_name = []
for keys in dicts:
if keys in files:
file_id.append(dicts[keys])
file_name.append(keys)

# ドキュメントのテキスト部分の取得
knowledge = {}
for id,name in zip(file_id,file_name):
document = docs_service.documents().get(documentId=id).execute()
content = document.get('body').get('content')

texts = []
for elem in content:
if 'paragraph' in elem:
for para_elem in elem['paragraph']['elements']:
text = para_elem['textRun']['content']
if "\n" != text:
texts.append(text)
texts = texts[6:]
knowledge[f"{name}"] = texts


.txtに変換



def sanitize_filename(file_name):
invalid_chars = r'[<>::"/\\|?*]'

if re.search(invalid_chars, file_name):
sanitized_name = re.sub(invalid_chars, '_', file_name)
sanitized_name = sanitized_name.strip()
return sanitized_name
else:
return file_name

for file_name,file_text in zip(knowledge.keys(),knowledge.values()):
if file_text:
sanitized_file_name = sanitize_filename(file_name)
file_path = os.path.join(path, "output", f"{sanitized_file_name}.txt")
with open(file_path,"w", encoding="utf-8") as file:
file.write(file_text[0])


このような手順を踏むことで、Google Documentファイルをテキストファイルに変換することが可能になります。

おわりに

ColabとGoogleドキュメントを連携させることで、クラウド上の文書データをプログラムで直接操作できるようになります。今回紹介した方法を使えば、Googleドキュメント内の情報をテキスト処理の素材として活用したり、機械学習の前処理に役立てることができます。


今後はこの方法を応用して、複数のドキュメントを一括で処理したり、取得した内容に自然言語処理(NLP)を加えるなど、さらに高度な分析にもつなげられるでしょう。


New call-to-action