0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python-docxとの出会い

Last updated at Posted at 2025-03-29

はじめに

これは書いてる人がPython-docxに出会ったときのことを記したものです。
書いてる人はpython初心者です。何か誤った情報の記載があれば悪しからず。

環境

  • OS: macOS Sequoia 15.3.1
  • エディタ: VScode
  • Pythonのバージョン: 3.9.6
    pythonのバージョンは3.7以降が好ましいそうです。

初対面

python-docxとの出会いは今年の2月下旬。
word上の文章を抽出したいな〜となって記事を読み漁ったところ、「それ、pythonで解決できるぜ」と天からの思し召しがあったので早速突撃。

install.py
pip install python-docx

お出迎え完了。

試してみる

まずはインポートから

import.py
from docx import Document

これでインポート完了。てなわけで早速テキストを表示してみましょう

sample.py
doc = Document("sample.docx") #wordファイルの読み取り

num = 1
for para in doc.paragraphs:
    print(num, para.text) #テキストを段落番号と一緒に表示
    num = num + 1

print("段落数: ", len(doc.paragraphs)) #段落数を表示

sample.docxには以下のような文章を書いてみたり引用したりしました。

スクリーンショット 2025-03-29 17.05.58.png

宮沢賢治「ポラーノの広場」より

実行ほいさっさ

$ sample.py
1 サンプルだぞ
2 
3 あのイーハトーヴォのすきとおった風、夏でも底に冷たさをもつ青いそら、うつくしい森
4 で飾られたモリーオ市、郊外のぎらぎらひかる草の波。  またそのなかでいっしょになっ
5 たたくさんのひとたち、ファゼーロとロザーロ、羊飼のミーロや、顔の赤いこどもたち、
6 地主のテーモ、山猫博士のボーガント・デストゥパーゴなど、いまこの暗い巨きな石の建
7 物のなかで考えていると、みんなむかし風のなつかしい青い幻燈のように思われます。で
8 は、わたくしはいつかの小さなみだしをつけながら、しずかにあの年のイーハトーヴォの
9 五月から十月までを書きつけましょう。
10 
段落数:  10

できました。やった〜
他にも画像や表も表示できたりするので色々試してみてください

参照元

python-docx公式
https://python-docx.readthedocs.io/en/latest/

python-docxの備忘録
https://qiita.com/dkclimb/items/6ce4896d755f7ad4acde

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?