こんな方におすすめ
- Pythonで、ツイッターのフォロワーをフォローしたい(相互フォローしたい)
- Pythonで、自分をフォローしてくれない人のフォローを外したい
- Pythonの集合の使い方を知りたい
ツイッターでフォロワーをフォローする。または、自分をフォローしてくれない人のフォローを外す。このような行為は、誰しもがよくするような動作です。Pythonプログラミングを描いて、自動化を実現してみましょう。
Pythonの集合の操作を使っておりますので、集合の使い方の参考にもしてみてください。
プログラムの内容
tweepyをインポートします。
1 |
import tweepy |
Consumer Key(CK),Consumer Secret Key(CS), Access Token(AK), Access Token Secret(AT)の設定。自分のツイッターの開発情報を入手して入れます。ツイッターのAPI関数を使用するので、以下のように設定します。
1 2 3 4 5 6 7 8 9 |
CK = "xxxxxx" CS = "xxxxxx" AK = "xxxxxx" AT = "xxxxxx" auth = tweepy.OAuthHandler(CK, CS) auth.set_access_token(AK, AT) api = tweepy.API(auth) my_info=api.me |
【世界で5万人が受講】実践 Python データサイエンス・オンライン講座
フォローワーをリストで入手します。下記では、Indexを500としているので、500名分フォロワーがリスト化されます。
1 2 3 4 5 6 7 8 9 10 |
index = 0 follower_list = [] for follower in tweepy.Cursor(api.followers).items(): print("screen_name:"+( follower.screen_name )+" name:"+(follower.name)) follower_list.append( follower.screen_name ) if index == 500: #人数を入力する break index += 1 |
次に、フォローしている人をリストで入手します。同じく500名分リスト化します。
1 2 3 4 5 6 7 8 9 10 |
index = 0 friends_list = [] for friends in tweepy.Cursor(api.friends).items(): print("screen_name:"+( friends.screen_name )+" name:"+(friends.name)) friends_list.append( friends.screen_name ) if index == 500: #人数を入力する break index += 1 |
リスト化した、follower_listとfriends_listを集合に変換します。
集合に変換することで、フォローしていないフォロワーや、フォローしているけどフォローされていない人を簡単に見つけることができます。
Pythonの集合の計算の例です。
集合A={A,B,C,D,E} 集合B={A,B,C}
集合Aー集合B={D,E}
1 2 3 |
#リストをset関数で集合に変換 follower_syugo=set(follower_list) friends_syugo=set(friends_list) |
集合の演算を用いることで、フォローしていないフォロワーを以下のように簡単に得ることができます。
また、同様に、フォローしているけど、フォローしてくれない人も得ることができる。
1 2 3 4 5 6 7 |
#フォローしていない、フォロワー nofollow_follower=follower_syugo-friends_syugo print(nofollow_follower) #フォローしてくれない、フォロワー nofollower_friends=friends_syugo-follower_syugo print(nofollower_friends) |
それぞれを集合からリストに変換する。(リストでループを回して、フォローまたアンフォローを実行するため。)
1 2 3 |
#集合からリストに変換 nofollow_follower_list=list(nofollow_follower) nofollower_friends_list=list(nofollower_friends) |
フォローしていない、フォロワーをフォローする。
1 2 |
for member in nofollow_follower_list: api.create_friendship(member) |
フォローしてくれない、フォロワーを外す。
1 2 |
for member in nofollower_friends_list: api.destroy_friendship(member) |
このプログラムを1週間おきに定期的に実行することで、相互フォローの状態を保つことができます。
まとめ
今回は、ツイッターの相互フォローを自動化するためのプログラムの描き方について説明しました。集合の使い方も理解できたと思います。
ぜひ、トライしてみてください。