0

我有一个包含关键字列表的文本文件 file1.txt。

python
dictionary
list
process
program

等等。

我正在使用官方 python youtube api 来搜索这些关键字;目前我正在手动进行。如何自动执行此操作,以便程序可以自动一个接一个地搜索这些关键字。

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)

编辑1:我按照你的要求做了。

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()

现在在输出中我得到 5 个空行而不是结果。

4

1 回答 1

0

为什么不使用(假设文件中的单词是换行符分隔)读入文本 words = open(FILENAME, 'r').read().split('\n')?然后,您可以使用 for 循环遍历此列表,for w in words:并在那里重复您的关键字搜索过程。

如果您想允许指定文件或手动输入单词,只需从标准输入中读取(请参阅How do you read from stdin in Python?

于 2014-06-07T17:06:45.940 回答