スキップしてメイン コンテンツに移動

一行でテキストに含まれるURLをすべて短縮URLに変換するPythonスクリプト

テキストに含まれるURLをすべてbit.lyの短縮URLに変換するPythonワンライナーを書いた。使用しているモジュールはre、urllib、urllib2、simplejson。コードに一行追加するだけだし、Twitterなどのメッセージを処理するのに便利だと思う。

for link in sorted(re.findall(r"(http(?:s?)\:\/\/(?!bit\.ly[\/\ ])[^\/\ ]+\/?.*?)(?:[\ <>\"\{\}\|\\\^\[\]\`]|$)", msg), reverse=True): msg = (lambda x: re.sub(re.escape(x), (lambda y: str(simplejson.loads(urllib2.urlopen("http://api.bit.ly/shorten?version=2.0.1&longUrl=%s&login=BITLY_ID&apiKey=BITLY_API_KEY" % urllib.quote(y)).read())["results"][y]["shortUrl"]))(x), msg))(link)

bit.lyのAPIキーは別途取得しておく必要がある。

msg = u"ここのブログのURLはhttp://handasse.blogspot.com/ です。記事のURLはhttp://handasse.blogspot.com/2010/05/urlurlpython.html です。"

としてURLを含むメッセージを処理すると以下のように変換される。

print msg ここのブログのURLはhttp://bit.ly/PQa9F です。記事のURLはhttp://bit.ly/cVRVu6 です。

上記のコードを展開したものが以下のコード。簡単なエラー処理を追加してある。

def bitly(x): try: data = urllib2.urlopen("http://api.bit.ly/shorten?version=2.0.1&longUrl=%s&login=BITLY_ID&apiKey=BITLY_API_KEY" % urllib.quote(x)).read() return str(simplejson.loads(data)["results"][x]["shortUrl"]) except: return x replace_url = lambda x: re.sub(re.escape(x), bitly(x), msg) links = sorted(re.findall(r"(http(?:s?)\:\/\/(?!bit\.ly[\/\ ])[^\/\ ]+\/?.*?)(?:[\ <>\"\{\}\|\\\^\[\]\`]|$)", msg), reverse=True) for link in links: msg = replace_url(link)

コメント