科学の箱

科学・IT・登山の話題

Python

automated the boring – day6

投稿日:2018年2月26日 更新日:

https://automatetheboringstuff.com/chapter11/

さてこの辺からようやく面白くなってくる。webscrapingをするにあたり、まずはブラウザをpythonから起動して目的のページを開く


import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
  # Get address from command line.
  address = ' '.join(sys.argv[1:])
  print(address)
else:
  # Get address from clipboard.
  address = pyperclip.paste()

webbrowser.open('https://www.google.com/maps/place/' + address)

次にブラウザを開かずにコンソールで完結するパターンでインターネット上のページを取得する。これができればweb scrapingはほぼ出来上がったといえるだろう。

>>> import requests
>>> res = requests.get('http://automatetheboringstuff.com/files/rj.txt')
>>> type(res)
<class 'requests.models.Response'>
>>> res.status_code== requests.codes.ok
True
>>> len(res.text)
174130
>>> print(res.text[0:250])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare
This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever. You may copy it, give it away or
re-use it under the terms of the Project

 

この続きとしてはダウンロードした内容をファイルに書き出す、タグを解析する、ブラウザを操作するといった例があるが、こちらは割愛。

https://automatetheboringstuff.com/chapter12/

さてブラウザの次はエクセルファイル。csv取り扱えれあ必要ないのではという、意見もある。しかし実際問題として企業のファイルはエクセルで用意されていてcsvであることはまれだ。エクセルファイルをpythonから操作できればユーザーへのファイル展開が簡単に実行できる。

>>> import openpyxl
>>> os.getcwd()
'C:\\temp\\pythonwork_01'
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet1'
>>> sheet['A1'].value
datetime.datetime(2015, 4, 5, 13, 34, 2)</blockquote>

 

https://automatetheboringstuff.com/chapter13/

13章ではPDFとwordを取り扱う。Excelも同じであるが、すでにパッケージが用意されているのでアプリケーションファイルだからといっても、面倒くさい手続きはほとんどない。テキストファイル読み込みと同じくらい簡単に読み込み、書き込みができるので、ちょっとしたアプリケーションならすぐに開発できる。

PDFを取り扱うのはPyPDF2。これはpip経由でパッケージをインストールした。


>>> import PyPDF2
>>> import os
>>> os.chdir('c:\\temp\pythonwork_01')
>>> pfo = open('meetingminutes.pdf', 'rb')
>>> pr = PyPDF2.PdfFileReader(pfo)
>>> po = pr.getPage(0)
>>> po.extractText()
'OOFFFFIICCIIAALL BBOOAARRDD MMIINNUUTTEESS Meeting of \nMarch 7\n, 2014\n \n
shall provide leadership and \ncreate policies for education that expand opportunities for c
advance Louisiana in an increasingly \ncompetitive glob\nal market.\n BOARD \n of ELEMENTARY

 

次にwordである。wordはdocxおよびreadDocxを使う。docxはpip経由でパッケージを導入した。

>>> import docx
>>> doc = docx.Document('demo.docx')
>>> len(doc.paragraphs)
7
>>> doc.paragraphs[0].text
'Document Title'
>>> doc.paragraphs[1].text
'A plain paragraph with some bold and some italic'
>>> import readDocx
>>> print(readDocx.getText('demo.docx'))
Document Title</blockquote>
A plain paragraph with some bold and some italic

Heading, level 1

Intense quote

first item in unordered list

first item in ordered list

メタ情報

inarticle



メタ情報

inarticle



-Python
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

K近傍法でデータを分析

K近傍法の手順 データ読み込み EDA スケーリング K選択前処理 モデル評価 K選択 モデル構築   K近傍法でデータを分析する際にはseabornのpairplotが役に立つ df = …

no image

condaでjupyter notebookが使えないとき

condaで環境を作るとjupyter notebookはインストールされていない。 この場合には個別にjupyterをインストールすればよい。   conda install jupyte …

no image

グリッドサーチ

機械学習のアルゴリズムを利用する際に一つの問題がパラメータの最適化。例えばSVMではガンマパラメータを適切に設定しないと結果は使い物にならないことがある。このパラメータは自分で設定する方法もあるが、P …

no image

kaggle Titanic Tutorial – 11

kaggleで人気があるlightGBMをつかってみる。   インストール pip install lightgbm 特に問題がなく終了。 コード、関係するところだけ記載。 split_be …

no image

タプルの操作

タプルはPythonで提供されているデータ構造の一つ。タプルは固定長で変更できない複数の値の集合である。 タプルオブジェクト (tuple object) — Python 3.8.0 ドキュメント …

2018年2月
« 1月   3月 »
 1234
567891011
12131415161718
19202122232425
262728  

side bar top



アーカイブ

カテゴリー