斬新で実用的なサードパーティのライブラリを見つけたら、もちろん共有する必要があります〜
プロット可能
Plottable は、matplotlib に基づいて美しいテーブルを描画するための Python ライブラリです。たとえば、下図のような形です。
コードは以下のように表示されます:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
from plottable import ColumnDefinition, Table
from plottable.formatters import decimal_to_percent
from plottable.plots import bar, percentile_bars, percentile_stars, progress_donut
cmap = LinearSegmentedColormap.from_list(
name="bugw", colors=["#ffffff", "#f2fbd2", "#c9ecb4", "#93d3ab", "#35b0ab"], N=256
)
fig, ax = plt.subplots(figsize=(6, 10))
d = pd.DataFrame(np.random.random((10, 4)), columns=["A", "B", "C", "D"]).round(2)
tab = Table(
d,
cell_kw={
"linewidth": 0,
"edgecolor": "k",
},
textprops={
"ha": "center"},
column_definitions=[
ColumnDefinition("index", textprops={
"ha": "left"}),
ColumnDefinition("A", plot_fn=percentile_bars, plot_kw={
"is_pct": True}),
ColumnDefinition(
"B", width=1.5, plot_fn=percentile_stars, plot_kw={
"is_pct": True}
),
ColumnDefinition(
"C",
plot_fn=progress_donut,
plot_kw={
"is_pct": True,
"formatter": "{:.0%}"
},
),
ColumnDefinition(
"D",
width=1.25,
plot_fn=bar,
plot_kw={
"cmap": cmap,
"plot_bg_bar": True,
"annotate": True,
"height": 0.5,
"lw": 0.5,
"formatter": decimal_to_percent,
},
),
],
)
plt.show()
ムービーピー
MoviePy はビデオ編集用の Python モジュールです。これを使用して、いくつかの基本的な操作 (ビデオのキャプチャ、スプライシング、字幕の追加など) やカスタムの高度な特殊効果などを実装できます。
ここで著者は、例として clips_array 関数を使用して、同じ画面に複数のビデオを同時に表示します。コードは以下のように表示されます:
from moviepy import editor
# margin: 设置外边距
video_clip = editor.VideoFileClip(r"demo.mp4").margin(10)
video_clip1 = video_clip.subclip(10, 20)
# editor.vfx.mirror_x: x轴镜像
video_clip2 = video_clip1.fx(editor.vfx.mirror_x)
# editor.vfx.mirror_y: y轴镜像
video_clip3 = video_clip1.fx(editor.vfx.mirror_y)
# resize: 等比缩放
video_clip4 = video_clip1.resize(0.8)
# 列表里面有两个列表,所以会将屏幕上下等分
# 上半部分显示video_clip1, video_clip2,下半部分显示video_clip3, video_clip4
clip = editor.clips_array([[video_clip1, video_clip2], [video_clip3, video_clip4]])
clip.ipython_display(width=600)
プロットリー・エクスプレス
Plotly Express は、非常に強力な Python オープン ソース データ視覚化フレームワークであり、インタラクティブな HTML ベースのチャートを作成して情報を表示し、さまざまな美しいアニメーション グラフを生成できます。ここで著者は、例として下の図に示すアニメーションを使用します。
コードは以下のように表示されます:
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
size="pop", color="continent", hover_name="country",
log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])
fig.show()
ユー・ゲット
You-Get は、非常に優れた Web サイトのビデオ ダウンロード ツールです。You-Getを使えば、インターネット上の動画や写真、音楽を簡単にダウンロードできます。
URLを入力して動画をダウンロードするだけ!
Autopep8
Autopep8 は、Python コードを PEP8 スタイルに自動的にタイプセットするツールです。pycodestyle プログラムを使用して、コードのどの部分をタイプセットする必要があるかを判断し、pycodestyle によって報告されたタイプセットの問題のほとんどを修正できます。
たとえば、次のコードです。
- 組版前:
import math, sys;
def example1():
####This is a long comment. This should be wrapped to fit within 72 characters.
some_tuple=( 1,2, 3,'a' );
some_variable={
'long':'Long code lines should be wrapped within 79 characters.',
'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
'more':{
'inner':'This whole logical line should be wrapped.',some_tuple:[1,
20,300,40000,500000000,60000000000000000]}}
return (some_tuple, some_variable)
def example2(): return {
'has_key() is deprecated':True}.has_key({
'f':2}.has_key(''));
class Example3( object ):
def __init__ ( self, bar ):
#Comments should have a space after the hash.
if bar : bar+=1; bar=bar* bar ; return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
- 組版後:
import math
import sys
def example1():
# This is a long comment. This should be wrapped to fit within 72
# characters.
some_tuple = (1, 2, 3, 'a')
some_variable = {
'long': 'Long code lines should be wrapped within 79 characters.',
'other': [
math.pi,
100,
200,
300,
9876543210,
'This is a long string that goes on'],
'more': {
'inner': 'This whole logical line should be wrapped.',
some_tuple: [
1,
20,
300,
40000,
500000000,
60000000000000000]}}
return (some_tuple, some_variable)
def example2(): return ('' in {
'f': 2}) in {
'has_key() is deprecated': True}
class Example3(object):
def __init__(self, bar):
# Comments should have a space after the hash.
if bar:
bar += 1
bar = bar * bar
return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
テキストブロブ
TextBlob は、Python で記述されたオープン ソースのテキスト処理ライブラリです。品詞タグ付け、名義成分抽出、感情分析、テキスト翻訳、スプライシング チェックなど、多くの自然言語処理タスクを実行するために使用できます。著者はここでスプライシング チェックを例として使用して説明します。興味のある友人は公式ドキュメントにアクセスして、TextBlob のすべての機能を読むことができます。
from textblob import TextBlob
b = TextBlob("I havv goood speling!")
print(b.correct()) #I have good spelling!
出力は次のとおりです: "I have good spelling!" ご覧のとおり、文中の単語が修正されています。
パイゲーム
Pygame は、SDL ライブラリに基づいて、ゲーム ソフトウェアの開発に使用される Python プログラム モジュールのセットです。Pygame を使用して、さまざまな機能の豊富なゲームやマルチメディア プログラムを実装できますが、同時に、複数のオペレーティング システムをサポートできる移植性の高いモジュールでもあります。
以下では、pygame を使用して小さな音楽プレーヤーを作成します。
from pygame import mixer
import pygame
import sys
pygame.display.set_mode([300, 300])
music = "my_dream.mp3"
mixer.init()
mixer.music.load(music)
mixer.music.play()
# 点击×可以关闭界面的代码
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
上記のコードを実行すると、コンピューターが音楽を再生します。
pyqrコード
pyqrcode は QR コードを生成するために使用されるサードパーティ製のモジュールで、コンソールに QR コードを出力したり、QR コードを画像として保存したりできますが、pypng パッケージに依存します。
例として、「Baidu クリック」で QR コードを生成すると、コードは次のようになります。
import logging
import os
import pyqrcode
logging.basicConfig(level = logging.DEBUG, format='%(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 生成二维码
qr = pyqrcode.create("http://www.baidu.com")
if not os.path.exists('qrcode'):
os.mkdir('qrcode')
# 生成二维码图片
qr.png(os.path.join('qrcode', 'qrcode.png'), scale=8)
# 在终端打印
print(qr.terminal(quiet_zone=1))