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

2025年4月20日 (日)

[Python]特定の文字列で終わる(終わらない)文字列を抽出する

正規表現で$記号は文字列の最後を表すため、これを正規表現パターンに利用する。以下の例では、複数の文字列からなるリストから、リスト内包表記を使用して、指定した正規表現パターンにマッチする(しない)要素を取り出している。

>>> import re
>>> ss = ['石見舞菜香', '鈴木みのり', '瀬戸麻沙美', 'のぐちゆり', '和多田美咲']
>>> # 「の」で始まる氏名
>>> [s for s in ss if re.search('^の', s)]
['のぐちゆり']
>>> # 「の」で始まらない氏名
>>> [s for s in ss if not re.search('^の', s)]
['石見舞菜香', '鈴木みのり', '瀬戸麻沙美', '和多田美咲']
>>> # 「の」を含むが「の」で始まらない氏名
>>> [s for s in ss if re.search('^.+の', s)]
['鈴木みのり']

ルックアラウンド式(lookaround expression)を使うこともできる。

>>> # 「の」で始まる氏名 ※肯定的な先読み
>>> [s for s in ss if re.search('^(?=の)', s)]
['のぐちゆり']
>>> # 「の」で始まらない氏名 ※否定的な先読み
>>> [s for s in ss if re.search('^(?!の)', s)]
['石見舞菜香', '鈴木みのり', '瀬戸麻沙美', '和多田美咲']

ルックアラウンド式については、以下のページの「Lookaround の概要」を参照のこと。

2025年4月16日 (水)

[R]インターネット上のファイルをダウンロードする

download.file関数を使う。第一引数にダウンロードしたいインターネット上のファイルをURLで、第二引数に保存するファイル名を指定する。以下は、2025年4月に、プロジェクト・グーテンベルクに掲載されている「赤毛のアン」の原著をテキストで納めているテキストファイルをダウンロードして、一時的なファイル名で保存した例。

当該ファイルは文字コードはUTF-8(BOM付き)、改行コードはCR+LFで保存されており、download.file関数のmodeオプションに"wb"を指定しないと、ダウンロード時に改行コードをCR+CR+LFに変換して保存するので注意(it does distinguish between text and binary files and for text transfers changes ‘\n’ line endings to ‘\r\n’ (aka ‘CRLF’).)。

> urlname <- "https://www.gutenberg.org/ebooks/45.txt.utf-8"
> filepath <- tempfile()
> download.file(urlname, filepath, mode = "wb")
URL 'https://www.gutenberg.org/ebooks/45.txt.utf-8' を試しています
Content type 'text/plain; charset=utf-8' length 606739 bytes (592 KB)
downloaded 592 KB

ダウンロードしたファイルを試しに読み込んでみる。最後に、ダウンローしたファイルは削除している。

> library(tidyverse)
> options(readr.show_progress = FALSE, readr.show_col_types = FALSE)
> lines <- read_lines(filepath, locale = locale(encoding = "UTF-8"))
> head(lines, 15)
[1] "The Project Gutenberg eBook of Anne of Green Gables"
[2] " "
[3] "This ebook is for the use of anyone anywhere in the United States and"
[4] "most other parts of the world at no cost and with almost no restrictions"
[5] "whatsoever. You may copy it, give it away or re-use it under the terms"
[6] "of the Project Gutenberg License included with this ebook or online"
[7] "at www.gutenberg.org. If you are not located in the United States,"
[8] "you will have to check the laws of the country where you are located"
[9] "before using this eBook."
[10] ""
[11] "Title: Anne of Green Gables"
[12] ""
[13] "Author: L. M. Montgomery"
[14] ""
[15] "Release date: June 27, 2008 [eBook #45]"
> tail(lines, 5)
[1] "including how to make donations to the Project Gutenberg Literary"
[2] "Archive Foundation, how to help produce our new eBooks, and how to"
[3] "subscribe to our email newsletter to hear about new eBooks."
[4] ""
[5] ""
> file.remove(filepath)
[1] TRUE

2025年4月 9日 (水)

[Python]文字列が指定の正規表現パターンとマッチするか否か調べる

reモジュールのsearch関数を使う。指定した正規表現パターンとマッチするとMatchオブジェクトを返し、マッチしないとNoneを返す。戻り値はブール型ではとそれぞれTrueとFalseになるので、そのままブール式として利用できる。

>>> import re
>>> s = '和多田美咲さん'
>>> print(re.search('美咲さん$', s))
<re.Match object; span=(3, 7), match='美咲さん'>
>>> print(re.search('^和', s))
<re.Match object; span=(0, 1), match='和'>
>>> print(re.search('和$', s))
None
>>> bool(re.search('美咲さん$', s))
True
>>> bool(re.search('和$', s))
False

複数を一度に調べたいときは、リストにしてリスト内包表記を使う。

>>> ss = ['石見舞菜香', '鈴木みのり', '瀬戸麻沙美', '和多田美咲']
>>> [s for s in ss if re.search('美', s)]
['瀬戸麻沙美', '和多田美咲']
>>> [s for s in ss if re.search('美$', s)]
['瀬戸麻沙美']
>>> [s for s in ss if re.search('希世乃', s)]
[]
>>> len([s for s in ss if re.search('美', s)])
2
>>> len([s for s in ss if re.search('希世乃', s)])
0

2025年4月 6日 (日)

[Python]OpenCVライブラリを使う

OpenCVライブラリを使うには、cv2モジュールを使えばよい。Anacondaにはデフォルトではインストールされていない。


>>> import cv2
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'cv2'
>>> ^Z

cv2モジュールを使うには、opencvパッケージをインストールする。


(base) >conda list | findstr "opencv"
(base) >conda install opencv
Channels:
- defaults
Platform: win-64
Collecting package metadata (repodata.json): done
Solving environment: done
## Package Plan ##
environment location: C:\Users\○○○\anaconda3
added / updated specs:
- opencv
The following packages will be downloaded:
(以下、表示省略)

試しに使ってみる。歌手・声優「優木かな」のXのアカウントから画像をダウンロードして「yukikana.jpg」と保存し、画像情報を取得して表示させてみる。


>>> import cv2
>>> img = cv2.imread('yukikana.jpg')
>>> print(img.shape)
(2000, 1333, 3)

Python_opencv_yukikana

2025年4月 5日 (土)

[Python]インターネット上のファイルをダウンロードする

requestsモジュールのget関数を使う。以下は、歌手・声優「優木かな」のXのアカウントから画像をダウンロードして「yukikana.jpg」と保存した例。ダウンロードしたファイルはImageモジュールのshow関数で画面に表示している。

>>> from PIL import Image
>>> import requests
>>> url = 'https://pbs.twimg.com/media/GLM7kq6boAAcJhA?format=jpg&name=large'
>>> f = open('yukikana.jpg', 'wb')
>>> r = requests.get(url)
>>> f.write(r.content)
189181
>>> f.close()
>>> image = Image.open(f.name)
>>> image.show()
Python_requests_yukikana

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

無料ブログはココログ

■■

■■■