我是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)
答案 0 :(得分:0)
只需更改设置点的行,就可以询问用户输入
points = input("Enter points ")
然后你的程序会询问用户这些积分。这不是使用argparser。当您的脚本变得更复杂时,您可以查看argparser。 https://docs.python.org/3/library/argparse.html
答案 1 :(得分:0)
要使用argparse
,您首先要声明ArgumentParser
对象,然后可以使用add_argument()
方法向对象添加参数。在此之后,您可以使用parse_args()
方法来解析命令行参数。
使用您的程序作为示例:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("word", help="the string to be searched")
# you will want to set the type to int here as by default argparse parses all of the arguments as strings
parser.add_argument("point", type = int)
args = parser.parse_args()
word = args.word
point = args.point
您将从命令行调用它,其顺序与添加命令的顺序相同,因此在您的情况下python your_program.py the 7
答案 2 :(得分:0)
如果要将其作为带参数的python脚本运行,则需要
if __name__ == '__main__':
...
告诉python运行以下内容。通过传递&#39; word&#39;可以从命令行运行以下命令:带有-w
或--word
标志的参数,以及&#39;点&#39;带有-p
或--points
标志的参数。例子:
C:\Users\username\Documents\> python jsonparser.py -w xerox -p 2
or
C:\Users\username\Documents\> python jsonparser.py --points 3 --word hello
以下是重构代码:
import argparse
from sys import argv
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
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
def _search_titles_for_keywords(data, word, s=[]):
for c in data:
if word in c['title'].lower():
s.append({'title' : c.get('title')})
return s
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
if __name__ == '__main__':
# create an argument parser, add argument with flags
parser = argparse.ArgumentParser(description='Search JSON data for `word` and `points`')
parser.add_argument('-w', '--word', type=str, required=True,
help='The keyword to search for in the titles.')
parser.add_argument('-p', '--points', type=int, required=True,
help='The points value to search for in the links.')
# parse the argument line
params = parser.parse_args(argv[1:])
url = "http://hn.algolia.com/api/v1/search_by_date?tags=story&numericFilters=created_at_i%3E1488196800,created_at_i%3C1488715200"
json_data = create_json_file_from_api(url)
print(json_data[:200]) #making sure the data pulled is correct
j = _build_array_of_necessary_data(json_data)
print(j) #testing the function above
k = _search_titles_for_keywords(j, params.word.lower())
print(k) #testing the function above
l = _search_links_for_point_value(j, params.points)
print(l)