0

I have a text file file1.txt that contains a list of keywords.

python
dictionary
list
process
program

and so on.

I'm using the official python youtube api to search for these keywords; which at present I'm doing manually. How to automate this such that the program can search for these keywords one after another automatically.

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
DEVELOPER_KEY = "BIzaSyCwzkEAWUFXvWq0u1hybEK3ZdlQw-YRg2w"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

# Call the search.list method to retrieve results matching the specified query term.
search_response = youtube.search().list(
  q=options.q,
  part="id,snippet",
  maxResults=options.max_results
).execute()
videos = []
for search_result in search_response.get("items", []):
  if search_result["id"]["kind"] == "youtube#video":
    videos.append("%s (%s)" % (search_result["snippet"]["title"],
                             search_result["id"]["videoId"]))
print "Videos:\n", "\n".join(videos), "\n"
keyword=raw_input("Enter the keyword you want to search video's for:")

if __name__ == "__main__":
  argparser.add_argument("--q", help="Search term", default=keyword)
  argparser.add_argument("--max-results", help="Max results", default=5)
  args = argparser.parse_args()

 try:
   youtube_search(args)
 except HttpError, e:
   print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

Edit 1: I did as you asked.

words = open('D:\keywordq.txt', 'r').read().split("\n")
for w in words:
  #keyword=raw_input("Enter the keyword you want to search video's for:")
  if __name__ == "__main__":
    argparser.add_argument("--q", help="Search term", default=w)
    argparser.add_argument("--max-results", help="Max results", default=5)
    args = argparser.parse_args()

Now in the output i get 5 blank lines instead of results.

Aaron Misquith
  • 621
  • 1
  • 7
  • 11

1 Answers1

0

Why not read in the text using (assuming the words in your file are newline delimited) words = open(FILENAME, 'r').read().split('\n')? Then you can iterate through this list using a for loop for w in words: and just repeat your keyword search process there.

If you want to allow either specifying a file OR manually entering words, just read from the standard input (see How do you read from stdin in Python?)

Community
  • 1
  • 1
Lgiro
  • 762
  • 5
  • 13