次のページを参考にしました。
Python 今更ながらTweepyを使って、Twitterを操作する
search_word.py
#! /usr/bin/python
#
# search_word.py
#
# Apr/26/2019
# ------------------------------------------------------------------
import sys
import tweepy
from key_tweepy import key_tweepy_proc
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
api = key_tweepy_proc()
word = ["グリム童話"]
set_count = 10
results = api.search(q=word, count=set_count)
for result in results:
username = result.user._json['screen_name']
user_id = result.id
print("ユーザーID:"+str(user_id))
user = result.user.name
print("ユーザー名:"+user)
tweet = result.text
print("ユーザーのコメント:"+tweet)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
key_tweepy.py
#
# key_tweepy.py
#
# Apr/26/2019
# ------------------------------------------------------------------
import tweepy
import os
from dotenv import load_dotenv
# ------------------------------------------------------------------
def key_tweepy_proc():
dotenv_path = '.env'
load_dotenv(dotenv_path)
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
access_token = os.environ.get("ACCESS_TOKEN")
access_token_secret = os.environ.get("ACCESS_TOKEN_SECRET")
#
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
return api
#
# ------------------------------------------------------------------
.env
CONSUMER_KEY = '******'
CONSUMER_SECRET = '******'
ACCESS_TOKEN = '******'
ACCESS_TOKEN_SECRET = '******'