質のいいフォローユーザーを探す【Twitter 自動化】

 twitterを運用するのにあたって,ちょっと自分でもそれ用の機能を作ってみました! social dogを使えばいいのですが...

実装した機能

  1. フォロワーを全て取得する
  2. フォローを全て取得する
  3. 1と2から相互フォローを取得する(差集合を使用)
  4. 1と2から片思いフォローを取得(自分だけフォローしている)
  5. 1~5を辞書型で保存して,jsonで出力

各機能の説明(めっちゃ雑)

  1. api.followers_ids()を使用
  2. api.friends_ids()を使用
  3. pythonの差集合を使用
    • 1.2で取得してきたものを一度set()を使い,集合にする
    • set(集合2).difference(集合1)を使い,差集合を求める
    • 上で求めた差集合をlist()のなかに入れてlist型に変換
  4. 片思いのリストをfor 文で回して,1.2同様にフォロー数とフォロワー数を取得する
  5. それぞれの関数の中で辞書に保存しているので,それをjsonで出力

コード

全てのフォロワーの取得

def GetAllFollow():
    global all_follow
    all_follow = api.friends_ids()
    memo['フォロー(' + str(len(all_follow)) + ')'] = all_follow
    print("フォロー取得終了")

全てのフォロワーを取得

def GetAllFollower():
    global all_follower
    all_follower = api.followers_ids()
    memo['フォロワー(' + str(len(all_follower)) + ')'] = all_follower
    print("フォロワー取得終了")

相互フォローを取得

def MutualFollow():
    temp = list(set(all_follow).intersection(set(all_follower)))
    memo['相互フォロー(' + str(len(temp)) + ')'] = temp
    print("相互フォローを取得")

片思いを取得

def UnrequitedFollow():
    global is_no_activeUser
    is_no_activeUser = list(set(all_follow).difference(set(all_follower)))
    memo['片側フォロー(' + str(len(is_no_activeUser)) + ')'] = is_no_activeUser
    print("片側フォローを取得")

jsonで出力

def main():
    GetAllFollow()
    GetAllFollower()
    UnrequitedFollow()
    MutualFollow()
    littleFF()
    with open('noActiveUser.json', 'w') as f:
        json.dump(memo, f, indent=4, ensure_ascii=False)

参考文献

docs.python.org

www.javadrive.jp