【发布时间】:2023-03-16 19:19:01
【问题描述】:
我对 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)
【问题讨论】: