- 1. Python3でUUIDを生成する
- 2. 動画圧縮する(MP4 to mp4) on python3
- 3. 地震波形データをPythonで読み込んでみよう
- 4. python async 実行記録
- 5. Jupyter RuntimeErrorの対処方法 asyncio.run() cannot be called from a running event loop
- 6. Python3: 接種状況ダッシュボードのデータを使ってワクチン接種済者をカウントする
- 7. 青空文庫を使ってネガポジ判定をやってみた
- 8. 【Twitcasting】気になるあの配信者の配信開始通知をdiscordに送信方法を考えて実装してみた。
- 9. Python Seleniumでスクレイピングする時、エラーが爆発
- 10. [python] seleniumのdeepL自動化
- 11. TF-IDFの基本的な考え方と実装方法
- 12. Bag of Words(BoW)の3つのやり方
- 13. pyenv-win環境でpipでインストールしたコマンドラインツールが使えない!時
- 14. Python3: 診療・検査医療機関の PDF を JSON に変換
- 15. 【6】「いかのおすし」を縦表記しよう
- 16. スクレイピングの基本的な流れ
- 17. Jupyterで特定のセルの入力と出力を参照する小ネタ
- 18. Django Import xxx could not be resolved from source エラーの解決方法
- 19. VSCode insiders venv activate時の「このシステムではスクリプトの実行が無効になっているため~」 エラーの解決
- 20. CentOS7 + Python3 + Mecab + Doc2VecでWikipediaのデータを解析した記録
Python3でUUIDを生成する
##はじめに
PythonでUUIDを生成する方法です。
本記事はPython3.8を使用しています。uuidというモジュールを使ってUUIDを生成するのですが、
Python3では標準ライブラリとしてバンドルされているので、
importしてすぐに使用できます。https://qiita.com/shimajiri/items/464275c5027ab09bc330
##UUIDとは
UUID(Universally Unique Identifier)とは、世界で同じ値を持つことがない一意な識別子です。##バージョン1
“`python
uuid.uuid1(node=None, clock_seq=None)
“`バージョン1は、時刻とMACアドレスを利用したUUIDで、
uuid1はホストID、シーケンス番号、現在時刻からUUIDを生成します。“`python
uuid.uuid1()
“`引数なしでも利用可能です。
nodeがなければuuid.getnode()で、ハードウェアアドレスを取得しそれが適用されます。clock_seq
動画圧縮する(MP4 to mp4) on python3
こんにちは.
実験動画を圧縮する機会が増えてきました.
実験の動画を撮影した場合は,拡張子「MP4」で記録されます.
結果を記載するページは「mp4」のみ許可されています.
といっても,自作のwikiなので,拡張子の権限を増やしてやればいいだけなのですが...まぁ,めんどくさいし,コマンド何回も打ち込むのだるいので,pythonで一気にやらしちゃおう!という内容です.
まず,ffmpegは必須です.
以下のコマンドでインストールしましょう.
※apt-get updateは行っておいた方が良いでしょう.“`
sudo apt-get install ffmpeg -y
“`私のPCにインストールしたffmpegのバージョン
少し古いかもしれません.“`
$ ffmpeg -version
ffmpeg version 4.3.2-0+deb11u2 Copyright (c) 2000-2021
the FFmpeg developers built with gcc 10 (Debian 10.2.1-6)
“`## ソースコード
“` vid
地震波形データをPythonで読み込んでみよう
# 本稿の方針
本稿では、地震波形データをPythonで読み込む方法についてご紹介します。Pythonを使って地震波形データを処理したい方に参考になればと思います。特に、地震の勉強・研究・業務をしてきた方で、Pythonを今まで使ってこなかった方や、反対に、Pythonは使いこなせる方で地震波形データに新たに手を出すような方々を想定しています。ちょっとしたフィルタリングや描画ができるようになったり、データ解析(機械学習を含む)のための基礎となったりしてお役に立てればと思います。
ここでは、自分で試した範囲のことを書いておくつもりです。網羅的な説明はしません。また、Pythonの説明などはしません。
(2022年1月25日追記)限定公開で同僚に内容を確認してもらいましたが、それほど問題なさそうなので、全体公開に切り替えました。
## 環境
Python 3系を使うことにします。今回はPython 3.7.2とObsPy 1.2.1を使っています。—
# ObsPyとは
[![alt](https://docs.obspy.org/_static/obspy-logo.
python async 実行記録
“`python
import asyncio
import timeasync def say_after(delay, what):
print(f”{time.strftime(‘%X’)} :{what}”)
await asyncio.sleep(delay)
print(f”{time.strftime(‘%X’)} :{what}”)async def main():
tasks = [say_after(3, ‘hello’), say_after(2, ‘yeeeei’), say_after(1, ‘ueeeeei’)]
await asyncio.gather(*tasks)asyncio.run(main())
“`
“`
16:38:20 :hello
16:38:20 :yeeeei
16:38:20 :ueeeeei
16:38:21 :ueeeeei
16:38:22 :yeeeei
16:38:23 :hello
“`
Jupyter RuntimeErrorの対処方法 asyncio.run() cannot be called from a running event loop
Jupyter自身のイベントループ上で新たにイベントループを開始しようとしたために起こったエラー。非同期処理を実行させたければ、await関数で直接実行させれば良い。
“`python:Jupyterで非同期処理を実行させる
import asyncio
import datetimeasync def display_date():
“””現在時刻を5秒間表示する”””
loop = asyncio.get_running_loop()
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if(loop.time()+1.0)>=end_time:
break
await asyncio.sleep(1)x : asyncio.run(display_date())
○ : await display_date()
“`
“`
2022-01-25 15:31:57.79
Python3: 接種状況ダッシュボードのデータを使ってワクチン接種済者をカウントする
デジタル庁の [接種状況ダッシュボード](https://info.vrs.digital.go.jp/dashboard/) のデータを処理して、ワクチン接種済者をカウントします。
データの取得
“`bash
wget https://data.vrs.digital.go.jp/vaccination/opendata/latest/summary_by_date.csv
“`次を計算します。
>ワクチン2回目接種済者
>ワクチン2回目接種後、6ヶ月が経過した者
>ワクチン3回目接種済者“`py:count_vaccination.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# csv_read.py
#
# Jan/25/2022
#
import sys
import csv
import datetime
#
from datetime import timedelta# ————————————————————-
青空文庫を使ってネガポジ判定をやってみた
# ネガポジ判定とは
文書のネガポジ判定(極性判定)とは、それぞれの文書が肯定的(ポジティブ)か否定的(ネガティブ)かを判定するタスクである。
ここでは抽出した単語のネガポジ判定をするために東北大学乾・鈴木研究室が提供している「日本語評価極性辞書」を活用する。
https://www.cl.ecei.tohoku.ac.jp/Open_Resources-Japanese_Sentiment_Polarity_Dictionary.html# 実装
必要なライブラリをインポート“`python
import zipfile
import urllib.request
import MeCab
import pandas as pd
import re
“`ネガポジ判定に使用するテキストを準備
“`python
# 青空文庫『吾輩は猫である』のファイルをダウンロード
urllib.request.urlretrieve(‘https://www.aozora.gr.jp/cards/000148/files/789_ruby_5639.zip’, ‘789_ruby_
【Twitcasting】気になるあの配信者の配信開始通知をdiscordに送信方法を考えて実装してみた。
#はじめに
趣味で推しの子がよくツイキャスするけど通知に気づけないからdiscordに投げるBotを作りました。
言語はPythonで書いてます。
記事の内容はほぼGitHubにあるものと同じです。メモ程度です。実際の稼働してる様子はこんな感じ。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2422677/431677b7-d048-f1d6-6c22-8c287106e785.png)#入れ方
とりあえず、[GitHub](https://github.com/renit0424/TwitcasNoticeDiscord)にあげてあります。
ダウンロード出来たら`confg.py`を編集して指定された値を入力します。
最後に`main.py`を実行すれば…
たぶん動きます。
Python Seleniumでスクレイピングする時、エラーが爆発
selenium 4.1.0でスクレイピングした時、エラーが多数発生する。
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=’C:/webdriver/chromedriver.exe’)
driver.get(‘https://www.yahoo.co.jp/’)
[python] seleniumのdeepL自動化
# 説明
pythonのseleniumをつかってdeepLという翻訳サイトを操作してファイルの中身を自動的に翻訳できたらよいと思って作ったもの。
バグが多くうまく動かないことが多いです
# 実行環境
* Intel(R) Core(TM) i7-8700 6コア12スレッド
* メモリ16GB
* windows10 64bit
* 仮想8コア、物理4コア
* Python 3.8.11
* ANACONDA
* JupyterLab 3.1.7#コード
## モジュール
“`python:modules
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
import urllib.parse
import os
from joblib import Parallel, delayed
from selenium.webdriver.common.by import By
f
TF-IDFの基本的な考え方と実装方法
# TF-IDF
### 概要
TF-IDF(Term Frequency-Inveerse Document Frequency)は、全ての文書に出現する単語と、一部の文書にしか出現しない単語を区別するための方法である。
Bag of Words(BoW)は各文書の単語ごとの出現回数をカウントしたものであるが、この方法では全ての文書に出現する単語と、一部の文書にしか出現する単語を区別することができない。### 数式による説明
以降の説明で使用する記号の意味は下記のとおり。+ $n_{d,t}$ :文書$d$で単語$t$が出現する回数
+ $df_{t}$ :単語$t$が出現する文書数
+ $N$ :全体の文書数
+ $T$ :1つの文書における単語数の合計#### TF
TFは、「1つの文書の中に現れる全単語の合計出現回数のうち、その1つの単語がどれだけの割合で出現したか」と定量化した指標である。したがって、ある1つの文書の1つの単語に対して定まる指標である。“`math
TF_{d,t} = \frac{n_{d,t}}{\sum_{t=1}^{T}n_{d,t}
Bag of Words(BoW)の3つのやり方
# Bag of Wordsとは
Bag of Words(BoW)は、各文書の形態素解析の結果をもとに、単語ごとの出現回数をカウントしたものである。
今回は、下記の3つの文書を対象にBoWを実行する。– 子供が走る
– 車が走る
– 子供の脇を車が走る*厳密には形態素は単語より小さな概念であるが、今回は単語として扱っている
# MeCabのインストール
形態素解析を行うための便利なライブラリにMeCabがある。
私はWidowsを使っているのだが、下記のサイトにお世話になった。
[MecabをインストールしてPythonで使う【Windows】](https://self-development.info/mecab%E3%82%92%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB%E3%81%97%E3%81%A6python%E3%81%A7%E4%BD%BF%E3%81%86%E3%80%90windows%E3%80%91/)# 1. 地道に行う方法
– 必要なライブラリをインポート“`py
pyenv-win環境でpipでインストールしたコマンドラインツールが使えない!時
pyenv-winでpath通してpip使えてるのに、pipでインストールしたパッケージ(jupyter等)が使えないときは、`shims`フォルダ除いてみてほしい。
“`:このパスは通ってる(これじゃ足りない)
%USERPROFILE%\.pyenv\pyenv-win\bin
%USERPROFILE%\.pyenv\pyenv-win\shims
“`ちなみにpipはここに入ってるからコマンドつかえる。pipでインストールされたパッケージは、ここじゃなくて、
“`:ここにインストールされる(このパスを追加すればいい)
%USERPROFILE%\.pyenv\pyenv-win\versions\3.x.x\Scripts
# versionは適当なバージョンを指定する
“`
Python3: 診療・検査医療機関の PDF を JSON に変換
次で公表されている PDF を JSON に変換します。
[診療・検査医療機関の公表について](https://www.pref.tochigi.lg.jp/e04/sinnryoukensa2.html)小山地区のデータを取得します。
“`bash
wget https://www.pref.tochigi.lg.jp/e04/documents/20220112225313.pdf
“`PDF の表示
“`bash
evince 20220112225313.pdf
“`![medical_jan24.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/4d70c5b8-6634-ca92-27d8-870c37520454.png)
変換
“`bash
pdftotext -layout 20220112225313.pdf
#
./medical_to_json.py 20220112225313.txt oyama_medical.json > tmp01
【6】「いかのおすし」を縦表記しよう
ファイルの名前は,「20211220_[自分の名前].py」でお願いします.
以下ターミナル実行時の出力例です.
“`
い
か
の
お
す
し
“`
https://gyazo.com/d275362db67f52ccd975376177047ee4
↑にも授業資料の演習提示時のgifがあります.
スクレイピングの基本的な流れ
# Webページをダウンロード
こちらサイト( https://codezine.jp/ )にアクセスしてみる。
Requestモジュールを使用する。Webブラウザの代わりにWebサイトにアクセスし、HTTPでデータの送受信を行ってくれる。“`python
import requests
r = requests.get(‘https://codezine.jp’)
“`下記のとおりstatus_codeを確認すると、アクセスに成功(200)していることが分かる。
“`python
print(r.status_code)
“`# Webページから要素を抜き出す
## BeautifulSoup4を使わない場合
ページの内容(HTML)を取得し、\タグと\ タグを取得してみた。
正規表現を使うこともできるが難しそう。“`python
text = r.text
for line in text.split(‘\n’):
if ‘‘ in line or ‘ ‘ in line:
print(li
Jupyterで特定のセルの入力と出力を参照する小ネタ
Jupyterで特定のセルの入力値や出力値を別のセルから参照する際の短いライトな小ネタです。
# 使うもの
– Python 3.9.0
– Jupyter (notebook==6.4.7)※本記事ではVS Code上のJupyterを使っていきますが普通のJupyter notebookやJupyterLabなどでも動作すると思われます。
# 直前のセルの出力値を取得する
アンダースコアの記号(`_`)を特定のセルで実行すると、直前に実行したセルの出力(notebookであれば`Out [n]:`といった表示になっている部分)を取ることができます。
“`py:セル1
x: int = 10 + 20
x
“`“`
30
“`“`py:セル2
y: int = x + 30
y
“`“`
60
“`“`py:セル3
_
“`“`
60
“`![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/228778/877a8116-9502
Django Import xxx could not be resolved from source エラーの解決方法
## 事象
プロジェクト作成、startappコマンド後、以下のエラーが発生した。
ようするに”django”関係がすべて読み込めていない。
“`Import “django.contrib” could not be resolved from source
Import “django.apps” could not be resolved from source
Import “django.db” could not be resolved from source
Import “django.shortcuts” could not be resolved from source“`
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2515586/2ae23339-e439-ef0b-08ce-535f5bf29042.png)## 環境
Windows 10
Python 3.10.2
Django 4.0.1
venv利用あり## 対処方法
Pythonの補完には
VSCode insiders venv activate時の「このシステムではスクリプトの実行が無効になっているため~」 エラーの解決
## 事象
PCを新調したのでPython開発環境を構築しようとvenv activate を実行しようとしたところ、
「このシステムではスクリプトの実行が無効になっているため、ファイル xxx .venv\Scripts\Activate.ps1 を読み込むことができません。」という
エラーになったので対処法を記載
別のPCではならなかったので調べるに至った![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2515586/dfb9afee-c6df-612c-97a7-fdc93df7723b.png)
## 環境
Windows 10
Visual Studio Code insiders 1.64.0
(Visual Studio Codeでも同じだと思う)
Python 3.10.2## 対処
Visual Studio Code insiders(以降、VSCode)の表示→コマンドパレットを押下し出てきた入力欄に「settings」と入力
![image.png](ht
CentOS7 + Python3 + Mecab + Doc2VecでWikipediaのデータを解析した記録
本稿では、ウィキペディアの各単語に対する類似単語ベスト10を、ウィキペディアから抽出した記録を可能な限り詳しく書きました。
#目次
[1.はじめに](#1-はじめに)
[2.本稿の目的](#2-本稿の目的)
[3.作業環境](#3-作業環境)
[4.最新のウィキペディアデータの取得](#4-最新のウィキペディアデータの取得)
[5.テキストデータを抽出](#5-テキストデータを抽出)
[6.pageとcategorylinksのデータをmysqlデータベースにインポート](#6-pageとcategorylinksのデータをmysqlデータベースにインポート)
[7.mecabの辞書に単語を追加](#7-mecabの辞書に単語を追加)
[8.テキストデータをmysqlデータベースに登録](#8-テキストデータをmysqlデータベースに登録)
[9.doc2vecを用いた機械学習で類似単語を抽出](#9-doc2vecを用いた機械学習で類似単語を抽出)
[10.目視での結果評価](#10-目視での結果評価)
[11.後処理](#11-後処理)
[12.スケジュール化](#12-スケジュー