我对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