Python」カテゴリーアーカイブ

プログラミング言語「Python」に関するカテゴリーです。

Pillow (Python Imaging Library)でPNGファイルを扱う時の注意

Pythonのライブラリ「Pillow」を使ってPNGファイルをJPGファイルに変換したい場合、次のようなスクリプトで実行できます。

from PIL import Image
Image.open('example.png').save('example.jpg')

ただし、PNGファイルにAlpha値が含まれていると次のようなエラーになってしまいます。

OSError: cannot write mode RGBA as JPEG

ということで、予めRGBAからRGBに変換しておくと、この問題を回避できます。

Image.open('example.png').convert('RGB').save('example.jpg')

リンク

Pillow: the friendly PIL fork
https://python-pillow.org/

PythonでURLのparse

Pythonのurllibを使うと簡単にURLをparseすることができます。

>>> import urllib.parse
>>> urlparse = urllib.parse.urlparse('http://www.example.com/python/?q1=example&q2=10')
>>> urlparse
ParseResult(scheme='http', netloc='www.example.com', path='/python/', params='', query='q1=example&q2=10', fragment='')
>>> urlparse.scheme
'http'
>>> urlparse.netloc
'www.example.com'
>>> urlparse.query
'q1=example&q2=10'

更に、queryをparseしたい場合はparse_qsを使うと便利です。

>>> urllib.parse.parse_qs(urlparse.query)
{'q2': ['10'], 'q1': ['example']}

リンク

urllib.parse — Parse URLs into components — Python 3.7.3 documentation
https://docs.python.org/3/library/urllib.parse.html

Pythonのdict型にドットアクセスを追加する方法

Pythonのdict型にJavaScript風のドット.アクセスを追加したい場合は__getattr____setattr__を使って実装できるそうです。

>>> class myDict(dict):
...   def __init__(self, **arg):
...     super(myDict, self).__init__(**arg)
...   def __getattr__(self, key):
...     return self.get(key)
...   def __setattr__(self, key, value):
...     self.__setitem__(key, value)
...
>>> d = myDict(one=1, two=2, three=3)
>>> d.one
1
>>> d.two = 20
>>> d.two
20

より本格的に使いたい場合は、いろいろなライブラリが公開されているようなので探してみるのも良いかなと思います。