#author("2024-04-30T12:44:17+09:00","default:irrp","irrp") #author("2024-04-30T12:44:42+09:00","default:irrp","irrp") →Python関連 →Pandas関連 →スクレイピング #contents *サブトピック [#g4de9318] -Python関連Tips一般 -Python文法系Tips -PythonでExcel制御 -Pythonのロギング -PythonのExe化 *並列処理、非同期処理 [#kaabfe78] -[[Pythonの非同期処理の基礎とOpenAI APIへ並列リクエストする実践例>https://zenn.dev/dev_commune/articles/19296b87231ea8]] 2024.4 -[[非同期処理をシンプルなPythonコードで説明する #Python - Qiita>https://qiita.com/y_kato_eng/items/ca0de5cf1224c807e7e5]] 2024.3 -[[Python Threading Module[並列処理]についての解説|メガゴリラ|note>https://note.com/mega_gorilla/n/n101748d37b07]] 2023.4 -[[Python で並行処理を駆使して実行時間を 40% 短縮する方法 - MOTEX TECH BLOG>https://tech.motex.co.jp/entry/2022/06/30/083000]] 2022.6 -[[Pythonの並列処理・並行処理をしっかり調べてみた - Qiita>https://qiita.com/simonritchie/items/1ce3914eb5444d2157ac]] 2019 *プロセス処理 [#o25fdff5] -[[シェルスクリプトとの対比で理解するPythonのsubprocess - 朝日ネット 技術者ブログ>https://techblog.asahi-net.co.jp/entry/2023/10/11/151441]] 2023.10 -[[Python3 Subprocess.Popen()とcommunicate()について - Qiita>https://qiita.com/ab-boy_ringo/items/934d18f244f40ddb3300]] 2023.6 -[[Pythonから完全に独立したプロセスを起動したい>https://teratail.com/questions/301382]] 2023.6 *設定ファイル [#p3f7a182] -[[Pythonで簡単に設定ファイルを使う。書き換え可能で、配列も辞書型も使う方法 - When it’s ready.>https://a2c.hatenablog.com/entry/20100816/1281891273]] 2010 -[[【Python】configファイルの読み込み・書き込みはconfigparserを使おう - 猫が蛇と戯れる>https://neko-py.com/python-configparser]] 2019 -[[Pythonの設定ファイル管理まとめ(settings / ini / json 形式別) [コピペサンプルコード付き] | KodoCode>https://kodocode.net/python-begin-settings/]] 2021 *ディレクトリ/ファイル操作 [#y0918c0d] -[[pathlibをもっと使おう - The jonki>https://www.jonki.net/entry/2024/02/17/232522]] 2024.2 -[[Pythonでimportの対象ディレクトリのパスを確認・追加(sys.pathなど) | note.nkmk.me>https://note.nkmk.me/python-import-module-search-path/]] 2023.10 -[[Pythonで容量の大きいCSVファイルを指定したサイズの複数ファイルに分割する | DevelopersIO>https://dev.classmethod.jp/articles/python-split-huge-size-file/]] 2023.8 -[[python - Disable SameFileError exception in shutil.copy - Stack Overflow>https://stackoverflow.com/questions/57083594/disable-samefileerror-exception-in-shutil-copy]] --You can force _samefile function to return False in every case. import shutil def my_same_file_diff_checker(*args, **kwargs): return False shutil._samefile = my_same_file_diff_checker shutil.copy("test.ini", "test.ini") -[[Python最新情報と勉強法(24) Pythonをローカル環境で開発するなら気を付けたいこととpathlibのすすめ | TECH+(テックプラス)>https://news.mynavi.jp/techplus/kikaku/python_learn-24/]] 2023.1 -[[Pythonで条件を満たすパスの一覧を再帰的に取得するglobの使い方 | note.nkmk.me>https://note.nkmk.me/python-glob-usage/]] 2018 glob(r"order_pdf\**\*.*", recursive=True) -[[Pythonでフォルダ内のファイルリストを取得する - Qiita>https://qiita.com/amowwee/items/e63b3610ea750f7dba1b]] 2017 -[[Python | ファイル名またはディレクトリ名を変更する>https://www.javadrive.jp/python/file/index16.html]] 2022 -[[【python】ファイルの条件を指定して一括移動する方法【コード解説】 | のんびり自習部屋>https://yuruikurashi.com/%e3%80%90python%e3%80%91%e3%83%95%e3%82%a1%e3%82%a4%e3%83%ab%e3%81%ae%e6%9d%a1%e4%bb%b6%e3%82%92%e6%8c%87%e5%ae%9a%e3%81%97%e3%81%a6%e4%b8%80%e6%8b%ac%e7%a7%bb%e5%8b%95%e3%81%99%e3%82%8b%e6%96%b9/]] 2021 -[[【Python入門】ディレクトリを簡単に作成する|os.mkdir・os.makedirs | 侍エンジニアブログ>https://www.sejuku.net/blog/63634]] 2022.9 --os.makedirs で深いところまで一回で作れる。すでにあってもエラーにならない *日付処理 [#ydfe775d] -[[Pythonで日時の文字列にタイムゾーンをつけるときの注意点 | DevelopersIO>https://dev.classmethod.jp/articles/python-strftime-tz/]] 2024.4 -[[strftimeメソッドでエラー(UnicodeEncodeError)が表示される - ガンマソフト>https://gammasoft.jp/support/python-datetime-strftime-unicodeencodeerror/]] 2019 --このエラーは、一般的な日本語版のWindowsでは発生しません。日本語版以外のWindowsパソコンをお使いの場合や言語・ロケールの設定を変更している場合に発生します。 --Pythonはstrftime()メソッドを処理するのに、Windows内のライブラリを使用します。そのため、Windowsシステムが日本語以外の場合、書式("%Y年%m月%d日")の中の日本語をエンコードできないので、UnicodeEncodeErrorを投げます。 import locale locale.setlocale(locale.LC_CTYPE, "Japanese_Japan.932") まだエラーが表示される場合はこちらも試してください。 locale.setlocale(locale.LC_CTYPE, "English_United States.932") -[[Pythonのdatetimeで日付の範囲を比較演算子で指定する - Qiita>https://qiita.com/Alice1017/items/4ce5be3f46aa34f9f900]] 2017 -[[【Python】文字列⇒日付、日付⇒文字列の変換(str, datetime)(備忘録) - Qiita>https://qiita.com/shinkai_/items/7a0e7e8c717f6001d366]] 2021.3 -[[Stop using utcnow and utcfromtimestamp>https://blog.ganssle.io/articles/2019/11/utcnow.html]] 2019 --datetime.utcnow()と datetime.utcfromtimestamp()は使うべからず。これはあなたの期待しているものではない。それよりもタイムスタンプ自身にUTCであることを認識させる datetime.now(tz=timezone.utc)と datetime.fromtimestamp(ts, tz=timezone.utc)を使うべし。 -[[Pythonにおける日本(東京)時刻の取得 ※Google colabでdatetimeを使用 - Qiita>https://qiita.com/hinata1119/items/0835dea5d16b70ea2b80]] 2022.11 -[[メモ:pythonで月末日を取得する方法 (月初日も追記) - Qiita>https://qiita.com/peketamin/items/c38de79e2a3946ec2358#datetimetimedeltadays1-%E3%82%92%E4%BD%BF%E3%81%86%E6%96%B9%E6%B3%95]] 2014 import calendar print calendar.monthrange(2014,12) -[[Pythonで月初・月末(初日・最終日)、最終X曜日の日付を取得 | note.nkmk.me>https://note.nkmk.me/python-datetime-first-last-date-last-week/]] 2019 -[[Pythonのdatetimeで日付や時間と文字列を変換(strftime, strptime) | note.nkmk.me>https://note.nkmk.me/python-datetime-usage/]] 2022.9 -[[Pythonで経過時間や日時(日付・時刻)の差分を測定・算出 | note.nkmk.me>https://note.nkmk.me/python-datetime-timedelta-measure-time/]] 2019 dt_now: date = datetime.now() # type: ignore dt_uri: date = parser.parse(a.expected_sales_date) # type: ignore td: timedelta = dt_uri - dt_now if td.days < 30: ... -[[Python 日付、時刻の処理 - Qiita>https://qiita.com/xza/items/9618e25a8cb08c44cdb0#%E6%97%A5%E4%BB%98%E3%81%AE%E5%8A%A0%E7%AE%97%E6%B8%9B%E7%AE%97]] 2018 -dateutil を使うには別途インストールが必要 --[[How to use dateutil.relativedelta in Python 3.x? - Stack Overflow>https://stackoverflow.com/questions/38792126/how-to-use-dateutil-relativedelta-in-python-3-x]] 2011 *文字列処理 [#vf28c157] -[[【Python】変数名と値を同時に表示する小技 - Qiita>https://qiita.com/yoshidashuntarou/items/f208c18fb54ba183790a]] 2023.9 --f"{v=}" -[[Python] 文字列を数値に変換(ただし空文字(None)はゼロとする) │ Web備忘録>https://webbibouroku.com/Blog/Article/py-convnum-default]] 2019 -[[全角文字と半角文字を含んだ文字列を正規化して表記ゆれを吸収する (normalize) - まくまくJavaScriptノート>https://maku77.github.io/js/string/normalize.html]] 2023.6 -[[Pythonで文字列をUnicode正規化(unicodedata.normalize) | note.nkmk.me>https://note.nkmk.me/python-unicodedata-normalize/]] -文字列に前ゼロでパティングする f"{s:0>7}" または s.zfill(7) -[[Pythonの文字列の改行方法と便利な操作まとめ | HEADBOOST>https://www.headboost.jp/python-n-strings/]] 2021 list = ["text1", "text2", "text3"] string = "\n".join(list) -[[【Python】 文字列定数について(stringモジュール) | Hbk project>https://hibiki-press.tech/python/built-in-types/string-constants/4104]] 2019 -[[Pythonのf文字列(フォーマット済み文字列リテラル)の使い方 | note.nkmk.me>https://note.nkmk.me/python-f-strings/]] 2018 -[[Pythonのf文字列の使い方 - ガンマソフト株式会社>https://gammasoft.jp/blog/python-f-string/]] 2021.9 -[[【python3】ファイル名に使用出来ない文字を変換する。 | [python-auto] 自動化の備忘録ブログ>https://python-auto.com/2020/07/12/%E3%80%90python3%E3%80%91%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D%E3%81%AB%E4%BD%BF%E7%94%A8%E5%87%BA%E6%9D%A5%E3%81%AA%E3%81%84%E6%96%87%E5%AD%97%E3%82%92%E5%A4%89%E6%8F%9B%E3%81%99%E3%82%8B/]] 2020.7 file_name = re.sub(r'[\\|/|:|?|.|"|<|>|\|]', '-', file_name) -[[図解!Python 正規表現の徹底解説!(文字列の抽出と置換など) - AI-interのPython3入門>https://ai-inter1.com/python-regex/]] 2022.9 -[[Pythonの文字列フォーマット(formatメソッドの使い方) - ガンマソフト株式会社>https://gammasoft.jp/blog/python-string-format/]] 2022.9 *PDFファイル [#gfa7e248] →PDF関連へ *CSVファイル [#n4269472] -[[pythonでのcsvファイルの読み込み - Qiita>https://qiita.com/motoki1990/items/0274d8bcf1a97fe4a869]] 2022.9 -CSVを辞書のリストに読み込んで特定の項目でソートするサンプル import csv rows =[]; #BOMありUTF8 なのでエンコーディングは utf-8-sig とした with open('./Anken.csv', 'r', encoding='utf-8-sig', errors='strict', newline='') as csv_file: f = csv.DictReader(csv_file, delimiter=',', doublequote=True, lineterminator='\r\n', quotechar='"', skipinitialspace=True) for row in f: rows.append(row) #破壊型ソートです rows.sort(key=lambda x:x['JOBNo.']) for row in rows: print(row['JOBNo.'], row['案件名']) *print()文 [#ib914079] -[[python で print() したものが出力されない理由>https://teratail.com/questions/274353]] 2020 -例:print('{}の税込価格は{:,d}円です'.format(fruit, fruit_price)) -[[printf 形式の文字列書式化 | 組み込み型 — Python 3.9 ドキュメント>https://docs.python.org/ja/3.9/library/stdtypes.html#printf-style-string-formatting]] 2022.4 --format % values (format は文字列) とすると、format 中の % 変換指定は values 中のゼロ個またはそれ以上の要素で置換されます。 --format が単一の引数しか要求しない場合、 values はタプルでない単一のオブジェクトでもかまいません。 --それ以外の場合、 values はフォーマット文字列中で指定された項目と正確に同じ数の要素からなるタプルか、単一のマップオブジェクトでなければなりません。 *メール送信 [#ha54ad85] -[[Pythonで複数の宛先にメールを送信する(Python3) - Qiita>https://qiita.com/bi-nonet/items/5104978238f1f5e72cc8]] 2014 -[[Pythonでメール送信 | Python学習講座>https://www.python.ambitious-engineer.com/archives/2034]] 2020 *pip [#z340a947] -[[Why you should use `python -m pip`>https://snarky.ca/why-you-should-use-python-m-pip/]] 2019 -- this blog post is meant to explain what python -m pip is and why you should be using it when you run pip. -[[Google Colabでpip installしたものを消えないようにする - Qiita>https://qiita.com/ezoalbus/items/d42d47685b592816054d]] 2021 -[[pip - How do I install Python packages in Google's Colab? - Stack Overflow>https://stackoverflow.com/questions/51342408/how-do-i-install-python-packages-in-googles-colab]] 2018 --Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line. *デバッグ [#d4943373] -[[Pythonにおける効率的なデバック方法入門 - MyEnigma>https://myenigma.hatenablog.com/entry/2015/05/25/221850]] 2023.5 -VSCode でライブラリの中でブレークしたい場合は、launch.json で configurations[n].justMyCode をfalseに設定すると、デバッガでライブラリのソースまで追いかけることが可能になる。 "justMyCode": false, *SQL/DB操作 [#a9995ea0] **SQLAlchemy [#zd249317] -[[SQLAlchemy2.0によるDB操作方法 - Qiita>https://qiita.com/yuuki_0524/items/77522cf958def6693c6d]] 2023.10 -[[SQLAlchemyとPandasでデータベースから任意データを取得する -雛形ソースコードあり-|はやぶさの技術ノート>https://cpp-learning.com/sqlalchemy-pandas/]] 2021 -[[SQLAlchemy から Pandas にデータを読み込む - Qiita>https://qiita.com/propella/items/6480f6c8ef612cd2283e]] 2020 **pyodbc [#p7393895] -[[【Python】pyodbc経由でSQL Serverにデータを追加する。 - Qiita>https://qiita.com/gaborotta/items/3f2f2fd492163a1ec007]] 2019 -[[PythonでSQL Serverに接続してSQLを実行する-スケ郎のお話>https://www.sukerou.com/2021/02/pythonsql-serversql.html]] 2021 -[[Python環境にpyodbcをインストールしてSQLServerに接続する手順 – Rainbow Engine>https://rainbow-engine.com/python-pyodbc-install/]] 2020 -[[PythonからSQL Serverを動かそう!〜接続編〜 - Qiita>https://qiita.com/wiskerpaddy/items/4268dfab09a6c53a64d1]] 2021 *AST [#t7205687] -[[ast --- 抽象構文木 — Python 3.10.6 ドキュメント>https://docs.python.org/ja/3/library/ast.html]] 2022.9 -[[dis --- Python バイトコードの逆アセンブラ — Python 3.10.6 ドキュメント>https://docs.python.org/ja/3/library/dis.html]] 2022.9 -[[たった1行から始めるPythonのAST(抽象構文木)入門>https://qiita.com/rhoboro/items/5bbaa3fa659ed7454d56]] 2020.12