« 2025年1月 | トップページ | 2025年3月 »

2025年2月28日 (金)

[Python]行列の和と差を求める

ndarray型に+演算子または-演算子を使う。行列の和と差の定義(行の数と列の数が同じ行列同士の各成分を足す、引く)から、二つの行列の行数と列数が一致しない場合はエラーが発生する。

>>> import numpy as np
>>> mxaa1 = np.array([[1, 2, 3], [6, 4, 2]])
>>> mxbb1 = np.array([[1, 1, 0], [2, 3, 8]])
>>> print(mxaa1)
[[1 2 3]
[6 4 2]]
>>> print(mxbb1)
[[1 1 0]
[2 3 8]]
>>> mxaa1 + mxbb1
array([[ 2, 3, 3],
[ 8, 7, 10]])
>>> mxaa2 = np.array([[1, 3], [2, 4]])
>>> mxbb2 = np.array([[7, 9], [5, 1]])
>>> print(mxaa2)
[[1 3]
[2 4]]
>>> print(mxbb2)
[[7 9]
[5 1]]
>>> mxaa2 - mxbb2
array([[-6, -6],
[-3, 3]])
>>> mxaa1 + mxbb2
Traceback (most recent call last):
File "", line 1, in
ValueError: operands could not be broadcast together with shapes (2,3) (2,2)
>>> mxaa1 - mxbb2
Traceback (most recent call last):
File "", line 1, in
ValueError: operands could not be broadcast together with shapes (2,3) (2,2)

2025年2月25日 (火)

[Python]行列を作る

numpyモジュールのarray関数を使う。引数にリストを指定すると、それがそのまま行列(ndarray型)になる。

>>> import numpy as np
>>> np.array([[1, 3, 5], [2, 4, 6]])
array([[1, 3, 5],
[2, 4, 6]])
>>> n = [[1, 2], [3, 4]]
>>> print(n)
[[1, 2], [3, 4]]
>>> np.array(n)
array([[1, 2],
[3, 4]])
>>> mx = np.array(n)
>>> type(mx)
<class 'numpy.ndarray'>

2025年2月24日 (月)

[Python]逆双曲線関数を使う

mathモジュールのasinh関数(逆双曲線正弦)、acosh関数(逆双曲線余弦)、atanh関数(逆双曲線正接)をそれぞれ使う。以下、動作例。

スクリプト

import math
d = [-0.8, -0.4, 0, 0.4, 0.8]
for i in range(len(d)):
print(f"asinh({d[i]:4}) = {math.asinh(d[i])}")
d = [1, 2, 3, 4, 5]
for i in range(len(d)):
print(f"acosh({d[i]:4}) = {math.acosh(d[i])}")
d = [-0.8, -0.4, 0, 0.4, 0.8]
for i in range(len(d)):
print(f"atanh({d[i]:4}) = {math.atanh(d[i])}")

画面出力

asinh(-0.8) = -0.732668256045411
asinh(-0.4) = -0.39003531977071526
asinh( 0) = 0.0
asinh( 0.4) = 0.39003531977071526
asinh( 0.8) = 0.732668256045411
acosh( 1) = 0.0
acosh( 2) = 1.3169578969248166
acosh( 3) = 1.762747174039086
acosh( 4) = 2.0634370688955608
acosh( 5) = 2.2924316695611777
atanh(-0.8) = -1.0986122886681098
atanh(-0.4) = -0.42364893019360184
atanh( 0) = 0.0
atanh( 0.4) = 0.42364893019360184
atanh( 0.8) = 1.0986122886681098

2025年2月23日 (日)

[Python]ファイルかディレクトリかを判定する

os.pathモジュールのisfile関数かisdir関数を使う。存在しないファイルやディレクトリを指定した場合は、例外が発生したりはせず単純にFalseが返される。

>>> import os
>>> os.path.isfile("C:\\Windows")
False
>>> os.path.isdir("C:\\Windows")
True
>>> os.path.isfile("C:\\Windows\\win.ini")
True
>>> os.path.isdir("C:\\Windows\\win.ini")
False
>>> os.path.isdir("C:\\macOS")
False
>>> os.path.isdir("C:\\Windows\\macOS.ini")
False

2025年2月22日 (土)

[Python]ファイルやディレクトリの存在を確認する

os.pathモジュールのexists関数を使う。exists関数はファイルかディレクトリかを判別することできないことに注意。ファイルとディレクトリを判別するには、isfile関数かisdir関数を使う。

>>> import os
>>> os.path.exists("C:\\Windows")
True
>>> os.path.exists("C:\\macOS")
False
>>> os.path.exists("C:\\Windows\\win.ini")
True
>>> os.path.exists("C:\\Windows\\macOS.ini")
False
>>> os.path.isfile("C:\\Windows")
False
>>> os.path.isdir("C:\\Windows")
True
>>> os.path.isfile("C:\\Windows\\win.ini")
True
>>> os.path.isdir("C:\\Windows\\win.ini")
False
>>> os.path.isfile("C:\\Windows\\macOS.ini")
False
>>> os.path.isdir("C:\\Windows\\macOS.ini")
False

2025年2月21日 (金)

[Python]ソースコードの文字コードを指定する

Pythonはソースコードが書かれたソースファイルの文字コードを、デフォルトではUTF-8としており、それ以外の文字コードで保存されている場合は、ソースファイルの読み込みに失敗する。ソースファイルの文字コードにUTF-8以外を使う場合は、ソースファイルの先頭に、以下の1行か2行を書けばよい。

その1

# coding=<encoding name>

その2

#!/usr/bin/python
# -*- coding: <encoding name> -*-

「<encoding name>」の箇所に文字コードを示す文字列を挿入する。Shift_JISであればcp932、shift_jisx0213などを書く。UTF-8であることを明示するのであればutf_8を指定する。

以下は、いずれもShift_JISで保存されたソースファイルcp932_1.pyとcp932_2.pyをそれぞれWindowsのコマンドプロンプトで実行した例。PythonはデフォルトをUTF-8としているため、最初の例では実行に失敗しているが、次の例のとおり文字コードを指定することで、問題なく実行できたことが分かる。

>type cp932_1.py
print('セナディア役の鈴木みのりさん、かわいい')
print('リフ役の瀬戸麻紗美さん、かわいい')
>type cp932_2.py
# coding=cp932
print('セナディア役の鈴木みのりさん、かわいい')
print('リフ役の瀬戸麻紗美さん、かわいい')
>python cp932_1.py
SyntaxError: Non-UTF-8 code starting with '\x83' in file ○○○\cp932_1.py on line 1, but no encoding declared; see https://python.org/dev/peps/pep-0263/ for details
>python cp932_2.py
セナディア役の鈴木みのりさん、かわいい
リフ役の瀬戸麻紗美さん、かわいい

文字コードの指定に使う文字列は、以下の一覧表が掲載されている。
https://docs.python.org/ja/3.13/library/codecs.html#standard-encodings

2025年2月20日 (木)

[Python]文字列が数値(小数)に変換できるか否か確認する

float関数と例外処理を利用して以下のような関数を定義すればよい。

ソースコード

def is_double(s):
try:
d = float(s)
except Exception:
return False
else:
return True
print(is_double("0"))
print(is_double(" -6"))
print(is_double(" -6.6 "))
print(is_double("-6e-6"))
print(is_double(""))
print(is_double("abc123"))

実行結果

True
True
True
True
False
False

2025年2月19日 (水)

[Python]文字列が数値(整数)に変換できるか否か確認する

int関数と例外処理を利用して以下のような関数を定義すればよい。

ソースコード

def is_integer(s):
try:
d = int(s)
except Exception:
return False
else:
return True
print(is_integer("0"))
print(is_integer(" -6"))
print(is_integer(" -6.6 "))
print(is_integer("-6e-6"))
print(is_integer(""))
print(is_integer("abc123"))

実行結果

True
True
False
False
False
False

2025年2月18日 (火)

[Anaconda]すべてのパッケージをアップデートする

updateサブコマンドに--allオプションをつけて実行する。「Proceed ([y]/n)?」で「y」をクリックすると、アップデートが始まる。

(base) >conda update --all
Channels:
- defaults
Platform: win-64
Collecting package metadata (repodata.json): done
Solving environment: done
## Package Plan ##
environment location: C:\Users\○○○\anaconda3
(表示省略)
Proceed ([y]/n)?
Downloading and Extracting Packages:
Preparing transaction: done
Verifying transaction: done
Executing transaction: done

2025年2月17日 (月)

[Python]数値を文字列に変換する

formatメソッドかフォーマット済み文字列リテラルを使う。

>>> n = -1
>>> d1 = -2
>>> d2 = 3.4
>>> print("|{}|{}|{}|".format(n, d1, d2))
|-1|-2|3.4|
>>> print("|{2}|{1}|{0}|".format(n, d1, d2))
|3.4|-2|-1|
>>> print("|{0:6d}|{1:.3f}|{2:.4e}|".format(n, d1, d2))
| -1|-2.000|3.4000e+00|
>>> print(f"|{n}|{d1}|{d2}|")
|-1|-2|3.4|
>>> print(f"|{n:6d}|{d1:.3f}|{d2:.4e}|")
| -1|-2.000|3.4000e+00|

2025年2月16日 (日)

[Python]小数点以下の切り上げを行う

mathモジュールのceil関数を使う。厳密には、引数に与えた数値より大きい最小の整数を返すことに注意。

>>> import math
>>> ds = [0.4, 0.5, 0.6, 1.4, 1.5, 1.6]
>>> for d in ds:
... print(f"{d} -> {math.ceil(d)}")
...
0.4 -> 1
0.5 -> 1
0.6 -> 1
1.4 -> 2
1.5 -> 2
1.6 -> 2
>>> ds = [-0.4, -0.5, -0.6, -1.4, -1.5, -1.6]
>>> for d in ds:
... print(f"{d} -> {math.ceil(d)}")
...
-0.4 -> 0
-0.5 -> 0
-0.6 -> 0
-1.4 -> -1
-1.5 -> -1
-1.6 -> -1

2025年2月15日 (土)

[Python]小数点以下の切り捨てを行う

mathモジュールのtrunc関数を使う。引数に与えた数値の小数点以下を、強制的に切り捨てていると考えればよい。

>>> ds = [0.4, 0.5, 0.6, 1.4, 1.5, 1.6]
>>> for d in ds:
... print(f"{d} -> {math.trunc(d)}")
...
0.4 -> 0
0.5 -> 0
0.6 -> 0
1.4 -> 1
1.5 -> 1
1.6 -> 1
>>> ds = [-0.4, -0.5, -0.6, -1.4, -1.5, -1.6]
>>> for d in ds:
... print(f"{d} -> {math.trunc(d)}")
...
-0.4 -> 0
-0.5 -> 0
-0.6 -> 0
-1.4 -> -1
-1.5 -> -1
-1.6 -> -1

似たような機能を持つfloor関数もあるが、こちらは小数点以下を強制的に切り捨てているのではなく、引数に与えた数値を超えない最大の整数を返すことに注意。つまり、負数の場合はtrunc関数とfloor関数では動作が異なる。

>>> import math
>>> ds = [0.4, 0.5, 0.6, 1.4, 1.5, 1.6]
>>> for d in ds:
... print(f"{d} -> {math.floor(d)}")
...
0.4 -> 0
0.5 -> 0
0.6 -> 0
1.4 -> 1
1.5 -> 1
1.6 -> 1
>>> ds = [-0.4, -0.5, -0.6, -1.4, -1.5, -1.6]
>>> for d in ds:
... print(f"{d} -> {math.floor(d)}")
...
-0.4 -> -1
-0.5 -> -1
-0.6 -> -1
-1.4 -> -2
-1.5 -> -2
-1.6 -> -2

2025年2月14日 (金)

[Anaconda]現在の仮想環境の情報を一覧表示する

condaコマンドのinfoサブコマンドを使う。

(base) >conda info
active environment : base
active env location : C:\Users\○○○\anaconda3
shell level : 1
user config file : C:\Users\○○○\.condarc
populated config files : C:\Users\○○○\anaconda3\.condarc
C:\Users\○○○\.condarc
conda version : 24.11.3
conda-build version : 24.9.0
python version : 3.12.7.final.0
(以下、表示省略)

2025年2月13日 (木)

[Python]小数点以下の四捨五入を行う

round関数を使う。JIS Z 8401に基づくいわゆる偶数丸めであることに注意。

>>> ds = [0.4, 0.5, 0.6, 1.4, 1.5, 1.6]
>>> for d in ds:
... print(f"{d} -> {round(d)}")
...
0.4 -> 0
0.5 -> 0
0.6 -> 1
1.4 -> 1
1.5 -> 2
1.6 -> 2
>>> ds = [-0.4, -0.5, -0.6, -1.4, -1.5, -1.6]
>>> for d in ds:
... print(f"{d} -> {round(d)}")
...
-0.4 -> 0
-0.5 -> 0
-0.6 -> -1
-1.4 -> -1
-1.5 -> -2
-1.6 -> -2

2025年2月12日 (水)

[Python]文字列を特定の文字または文字列で分割する

reモジュールのsplit関数を使う。2番目の例のとおり、正規表現を使って分割の条件を指定することができる。

>>> import re
>>> s = '石見舞菜香,鈴木みのり , 野口瑠璃子, 安野希世乃 ,和多田美咲'
>>> re.split(',', s)
['石見舞菜香', '鈴木みのり ', ' 野口瑠璃子', ' 安野希世乃 ', '和多田美咲']
>>> re.split('[ ,]+', s)
['石見舞菜香', '鈴木みのり', '野口瑠璃子', '安野希世乃', '和多田美咲'

 

2025年2月11日 (火)

[Python]等差数列を作成する

numpyモジュールのarange関数を使う。戻り値はndarrayクラス。初項1、公差2、末項9の等差数列を求めてみる。arangeの第二引数には、「末項+1」の値を指定する必要があることに注意。

>>> import numpy as np
>>> type(np.arange(1, 9 + 1, 2))
<class 'numpy.ndarray'>
>>> np.arange(1, 9 + 1, 2)
array([1, 3, 5, 7, 9])
>>> n = np.arange(1, 9 + 1, 2)
>>> n[0]
1
>>> print(n)
[1 3 5 7 9]
>>> type(n[0])
<class 'numpy.int32'>

以下の例のとおり第二引数の値を超えない値まで項が求まり、小数を指定することもできる。三つの値の組合せで項数が0となるような場合は何も返さない。公差に負数を指定することもできる。引数に与えた数値リテラルによって戻り値の型が自動で決まることに注意。

>>> np.arange(2.2, 3.3, 0.2)
array([2.2, 2.4, 2.6, 2.8, 3. , 3.2])
>>> d = np.arange(2.2, 3.3, 0.2)
>>> type(d[1])
<class 'numpy.float64'>
>>> np.arange(1, 10 + 1, 2)
array([1, 3, 5, 7, 9])
>>> np.arange(20, 10, 2)
array([], dtype=int32)
>>> np.arange(20, 10, -1)
array([20, 19, 18, 17, 16, 15, 14, 13, 12, 11])

2025年2月10日 (月)

[Python]アメリカ合衆国大統領の大統領就任演説のテキストを得る

nltkモジュールを使う。初代のワシントンから、2021年就任のバイデン大統領までが含まれている。

>>> import nltk
>>> from nltk.corpus import inaugural
>>> ss = nltk.corpus.inaugural.fileids()
>>> len(ss)
59
>>> ss[0:3]
['1789-Washington.txt', '1793-Washington.txt', '1797-Adams.txt']
>>> ss[-1:-5:-1]
['2021-Biden.txt', '2017-Trump.txt', '2013-Obama.txt', '2009-Obama.txt']

試しに、2009年に就任したオバマ大統領の一部を表示してみる。

>>> ss[-4]
'2009-Obama.txt'
>>> s = inaugural.raw(ss[-4])
>>> s[0:70]
'My fellow citizens:\n\nI stand here today humbled by the task before us,'

新聞社のウェブサイトの記事でも公開されており、一致していることが確認できる。
http://www.asahi.com/special/081113/TKY200901200391.html

2025年2月 9日 (日)

[Python]NLTKのパッケージをダウンロードする

nltkモジュールのdownloadメソッドを使う。

>>> import nltk
>>> nltk.download()
showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml

次のウィンドウが開く。

Python_nltk_downloader1

「Collections」タブの「Identifier」の「all」をクリックして選択し、左下の「Download」ボタンをクリックすると、ダウンロードが始まる。数分待つとダウンロードが完了して次のようになるはず。

Python_nltk_downloader2

ウィンドウを終了すると、コンソール画面は以下のようになるはず。

True

試しに使ってみる。

>>> from nltk.book import *
*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4: Inaugural Address Corpus
text5: Chat Corpus
text6: Monty Python and the Holy Grail
text7: Wall Street Journal
text8: Personals Corpus
text9: The Man Who Was Thursday by G . K . Chesterton 1908

text1やtext2がサンプルデータ。

>>> len(text1)
260819
>>> text1[0]
'['
>>> text1[1]
'Moby'
>>> text1[0:7]
['[', 'Moby', 'Dick', 'by', 'Herman', 'Melville', '1851'

2025年2月 8日 (土)

[Python]エラーメッセージ「UnicodeDecodeError: 'cp932' codec can't decode byte 0x○ in position ○: illegal multibyte sequence」

Windowsの対話型実行環境で、あらかじめ作成したスクリプトを読み込んで実行しようとして、このようなエラーメッセージができることがある。これは、ファイルの文字コードを正しく指定していないことが原因。Windows版はShift_JISであることを前提に動作しているため、UTF-8で保存されたファイルとそのまま読み込もうとすると、このエラーメッセージが表示される。

以下は、以下の2行からなるスクリプトを作成してShift_JISでprintsjis.py、UTF-8でprintutf-8.pyとして保存しておく。

print('セナディア役の鈴木みのりさん、かわいい。')
print('リフ役の瀬戸麻沙美さん、かわいい。')

対話型実行環境を起動し、それぞれのスクリプトを読み込んで実行する。ファイルの文字コードを指定しないとShift_JISとして読み込むため、encodingオプションを使用して文字コードを指定して読み込んでいる。

>python
Python 3.11.7 | packaged by Anaconda, Inc. | (main, Dec 15 2023, 18:05:47) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exec(open('printsjis.py').read())
セナディア役の鈴木みのりさん、かわいい。
リフ役の瀬戸麻沙美さん、かわいい。
>>> exec(open('printutf-8.py').read())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'cp932' codec can't decode byte 0x○ in position ○: illegal multibyte sequence
>>> exec(open('printutf-8.py', encoding = 'UTF-8').read())
セナディア役の鈴木みのりさん、かわいい。
リフ役の瀬戸麻沙美さん、かわいい。

2025年2月 7日 (金)

[Python]対話型実行環境でバージョンを確認する

sysモジュールを利用する

>>> import sys
>>> print(sys.version)
3.9.16 (main, Mar 8 2023, 10:39:24) [MSC v.1916 64 bit (AMD64)

 

2025年2月 6日 (木)

[Python]コマンドラインでバージョンを確認する

-Vオプションを使う。-VVとすると(when given twice, print more information about the build)、より詳細な情報を表示する。

>python -V
Python 3.9.16
>python -VV
Python 3.9.16 (main, Mar 8 2023, 10:39:24) [MSC v.1916 64 bit (AMD64)]

2025年2月 5日 (水)

[Python]バイト列リテラルからbytes型変数を作成する

文字列リテラルの前に接頭辞bを付ければよい。ただし、接頭辞bでは日本語を服もバイト列リテラルを作成できない。bytes関数を使うことであらゆる文字からなるバイト列文字列を作成することができる。ただし文字コードを指定する必要がある。

バイト列リテラルはprint関数の出力では、接頭辞bが付く。最後の例のとおりにバイト列を文字列に変換する場合はdecodeメソッドを使う。

>>> s = 'Watada Misaki'
>>> by = b'Watada Misaki'
>>> print(s)
Watada Misaki
>>> print(by)
b'Watada Misaki'
>>> s = '和多田美咲'
>>> by = bytes('和多田美咲', 'utf-8')
>>> print(s)
和多田美咲
>>> print(by)
b'\xe5\x92\x8c\xe5\xa4\x9a\xe7\x94\xb0\xe7\xbe\x8e\xe5\x92\xb2'
>>> by = bytes('和多田美咲', 'Shift_JIS')
>>> print(by)
b'\x98a\x91\xbd\x93c\x94\xfc\x8d\xe7'
>>> print(by.decode('Shift_JIS'))
和多田美咲

2025年2月 3日 (月)

[Python]文字列のハッシュ値を得る

hashlibモジュールの関数を使う。関数はハッシュオブジェクトというハッシュ値を格納したオブジェクトを返すので、関数を指定して戻り値を決める。

>>> import hashlib
>>> s = "鈴木みのり"
>>> md5 = hashlib.md5(s.encode()).hexdigest()
>>> print(md5)
2cdcdf384125ac19c173e9517b23847b
>>> sha1 = hashlib.sha1(s.encode()).hexdigest()
>>> print(sha1)
728d6a009b1700f9759ed2b502a0f673820700d5
>>> sha256 = hashlib.sha256(s.encode()).hexdigest()
>>> print(sha256)
4a806bf1e967f0764841aabcb3e634316f4b19be1dc9244480cd2c26c315db2b

2025年2月 2日 (日)

[R]画像の大きさを変える

magickパッケージのimage_resize関数を使う。元の画像をmagick-image型で用意して、この関数に当てはめればよい。

以下は、声優瀬戸麻沙美の公式ウェブサイトのページから画像ファイルをダウンロードしてパソコン内に保存し、その画像の大きさを変えた例。アップロードされているオリジナルの画像(横660ピクセル、縦906ピクセル)を縦横50%ずつ縮めている。~1.pngがオリジナル、~2.pngが縦横50%に縮めた画像。

> library(magick)
> im <- image_read("https://www.starcrew.co.jp/wp-content/uploads/2022/11/TALENT02.jpg")
> print(im)
format width height colorspace matte filesize density
1 JPEG 660 906 sRGB FALSE 260047 72x72
> image_write(im, "R_magick_SetoAsami1.png")
> im <- image_resize(im, geometry = "50%")
> print(im)
format width height colorspace matte filesize density
1 JPEG 330 453 sRGB FALSE 0 72x72
> image_write(im, "R_magick_SetoAsami2.png")

R_magick_setoasami1R_magick_setoasami2

左:R_magick_SetoAsami1.png、右:R_magick_SetoAsami2.png

« 2025年1月 | トップページ | 2025年3月 »

無料ブログはココログ

■■

■■■