我有一个包含关键字列表的文本文件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条空行而不是结果。
最佳答案
为什么不使用读取文本(假设文件中的单词以换行符分隔)words = open(FILENAME, 'r').read().split('\n')
?然后,您可以使用for循环for w in words:
遍历此列表,并在此重复您的关键字搜索过程。
如果要允许指定文件或手动输入单词,只需从标准输入中读取(请参阅How do you read from stdin in Python?)
关于python - Python程序将文本文件的输入发送到youtube搜索api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24099412/