2014-06-07 51 views
0

我有一個包含關鍵字列表的文本文件file1.txt。Python程序將文本文件的輸入發送給YouTube的搜索API?

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空行而不是結果。

回答

0

爲什麼不用文字閱讀(假設文件中的文字是換行符分隔的) words = open(FILENAME, 'r').read().split('\n')?然後,您可以使用for循環for w in words:遍歷這個列表,然後在那裏重複您的關鍵字搜索過程。

如果你想允許任何指定的文件或手動輸入的話,剛剛從標準輸入讀取(見How do you read from stdin in Python?

+0

我嘗試使用** read.split(「\ n」)**,它的工作第一次,但後來開始得到消息** AttributeError:'builtin_function_or_method'對象沒有屬性'分裂'** –

+0

對不起,我打錯輸入的例子。閱讀後應該有parens。它現在固定,應該工作。 – Lgiro

+0

您是否嘗試在循環中打印每個單詞以確保多數按預期工作? – Lgiro