2017-03-07 137 views
0

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

如果你想运行此作为带有参数的Python脚本,你需要有

if __name__ == '__main__': 
    ... 

告诉python运行下面的内容。可以通过将'word'参数与-w--word标志以及'点'参数与-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) 
+0

谢谢你,但我怎样才能得到一个名单,只有符合点搜索和关键字匹配的标题? 会是:对于a,b在zip(k,l)中:print(a,b) 在代码的末尾? – KRose

0

只要改变你在哪里设置点询问用户输入行

points = input("Enter points ") 

那么你的程序会询问用户的点。尽管这不是使用argparser。当你的脚本变得更复杂,有更多的输入选项时,你可以看看argparser。 https://docs.python.org/3/library/argparse.html

+0

我想这样做,但我希望它在命令行中运行,使其更容易访问 – KRose

0

要使用​​你首先要声明的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

欲了解更多信息,从命令行调用它见:https://docs.python.org/3/howto/argparse.html

+0

我明白这远远超过其他解释相关更好我遇到过其他地方,但如何运行这个_main_的实例,它结合了点和词的结果? – KRose