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:、そこでキーワード検索プロセスを繰り返すことができます。

ファイルを指定するか、手動で単語を入力できるようにしたい場合は、標準入力から読み取るだけです ( Python で stdin から読み取る方法を参照してください) 。

于 2014-06-07T17:06:45.940 に答える