我對python完全陌生,現在從未使用它。我被困在這個程序中,它假設是一個命令行程序,要求關鍵字,然後在可用標題列表中搜索它們。我用json將api的信息加載到字典中,並能夠搜索它。創建解析器代碼
我的主要問題是,我不知道如何做argparser,這將允許我使它成爲一個命令行程序。
幫助?
下面是我對到目前爲止的代碼:
import requests
import argparse
import json
from urllib.request import urlopen
def create_json_file_from_api(url):
request = urlopen(url)
data = request.read().decode("utf-8")
j_data = json.loads(data)
return j_data
json_data = create_json_file_from_api("http://hn.algolia.com/api/v1/search_by_date?tags=story&numericFilters=created_at_i>1488196800,created_at_i<1488715200")
print(json_data) #making sure the data pulled is correct
def _build_array_of_necessary_data(data, d=[]):
if 'hits' in data:
for t in data['hits']:
d.append({'title' : t.get('title'), 'points': t.get('points'), 'url' : t.get('url')})
_build_array_of_necessary_data(t,d)
return d
j = _build_array_of_necessary_data(json_data)
print(j) #testing the function above
def _search_titles_for_keywords(data, word, s=[]):
for c in data:
if word in c['title']:
s.append({'title' : c.get('title')})
return s
word = "the" #needs to be input by user
word.upper() == word.lower()
k = _search_titles_for_keywords(j, word)
print(k) #testing the function above
def _search_links_for_point_value(data, points, s=[]):
points = int(points)
for c in data:
if points <= c['points']:
s.append({'Title of article is' : c.get('title')})
return s
points = "7" #needs to be input by user
l = _search_links_for_point_value(j, points)
print(l)
謝謝你,但我怎樣才能得到一個名單,只有符合點搜索和關鍵字匹配的標題? 會是:對於a,b在zip(k,l)中:print(a,b) 在代碼的末尾? – KRose