2017-03-07 135 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