エンジニアリングとお金の話

都内で働くエンジニアの日記です。

【技術】俺が選ぶ地味に便利なpythonライブラリトップ3

【SPONSORED LINK】

最近プライベートで開発を行う際は、ほぼpythonでプログラミングを行っている。pythonは標準ライブラリが豊富である為、自分のやりたい事が簡単に書け重宝している。

なお、仕事ではjavaを使って開発を行っている為、pythonで簡単に出来た事がjavaではゴリゴリ実装しないといけなくてアーーーとなる事が多い。数あるpythonライブラリの中で、これ便利!と言うものを3つ紹介したい。

1.collectionsモジュールのCounter

単語の数を数えたい場合等に使用。
サンプルはこちら↓

#-*- coding:utf-8 -*-
from collections import Counter
import re

#この文章の中から出現頻度が高い単語を5つ取得する
words = """Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma, which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice, heart and intuition. They somehow already know what you truly want to become"""

print Counter([line.lower() for line in re.findall("(\w+'\w+|\w+)",words)]).most_common(5)

処理結果

[("don't", 3), ('is', 2), ('your', 2), ('living', 2), ('of', 2)]

2.dictモジュールのsetdefault

ディクショナリに配列を格納したい場合に使用。
サンプルはこちら↓

#-*- coding:utf-8 -*-
from collections import Counter
import re

wordDict=dict()

#頭文字が同じ単語ごとにディクショナリに纏める(キー:頭文字、値:単語の配列)
words = """Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma, which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice, heart and intuition. They somehow already know what you truly want to become"""

for line in [line.lower() for line in re.findall("(\w+'\w+|\w+)",words)]:
    wordDict.setdefault(line[0],[]).append(line)
print wordDict

処理結果

{'a': ['and', 'already'], 'b': ['be', 'by', 'become'], 'e': ["else's"], 'd': ["don't", "don't", 'dogma', "don't", 'drown'], 'i': ['is', 'it', 'is', 'inner', 'intuition'], 'h': ['heart'], 'k': ['know'], 'l': ['limited', 'living', 'life', 'living', 'let'], 'o': ['of', 'other', 'of', 'others', 'opinions', 'out', 'own'], 'n': ['noise'], 'p': ["people's"], 's': ['so', 'someone', 'somehow'], 'r': ['results'], 't': ['time', 'trapped', 'the', 'thinking', 'the', 'they', 'truly', 'to'], 'w': ['waste', 'which', 'with', 'what', 'want'], 'v': ['voice'], 'y': ['your', 'your', 'you']}

3.osモジュールのwalk

フォルダの中を再帰的に処理したい場合に使用。
サンプルはこちら↓

#-*- coding:utf-8 -*-
import os

#d:\test0配下の全てのファイル名を取得する。(フルパス表示)
for dirpath,dirname,filenames  in os.walk("d:\\test0"):
    for filename in filenames:
        print "%s\%s" % (dirpath,filename)

処理結果

d:\test0\test1\test1_1\test1.txt
d:\test0\test2\test2_1.txt
d:\test0\test2\test2_2.txt
d:\test0\test3\test3_1.txt
d:\test0\test3\test3_2.txt
d:\test0\test3\test3_3.txt

※今回試したフォルダ構成はこちら↓
D:\TEST0
├─test1
│ └─test1_1
│ test1.txt

├─test2
│ test2_1.txt
│ test2_2.txt

└─test3
test3_1.txt
test3_2.txt
test3_3.txt

まだまだ便利なモジュールが多数存在すると思うので今後も少しずつ知識を増やして行きたい。