【问题标题】:Python program to send the input of text file to youtube search api?Python程序将文本文件的输入发送到youtube搜索api?
【发布时间】:2014-06-07 16:44:41
【问题描述】:

我有一个包含关键字列表的文本文件 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 个空行而不是结果。

【问题讨论】:

    标签: python python-2.7 youtube pyscripter


    【解决方案1】:

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

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

    【讨论】:

    • 我尝试使用 read.split('\n'),它第一次工作但随后开始收到消息 AttributeError: 'builtin_function_or_method' object has no attribute '分裂'
    • 对不起,我打错了例子。阅读后应该有括号。它现在已修复,应该可以使用。
    • 您是否尝试打印循环中的每个单词以确保大部分内容按预期工作?
    • 我尝试打印每个单词,但只会打印第一个。
    猜你喜欢
    • 2013-12-06
    • 2021-07-03
    • 2016-10-04
    • 2021-08-16
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多