2017-03-07 1 views
0

저는 파이썬에 완전히 익숙하지 않았으며 지금까지는 그 일을 해본 적이 없습니다. 나는이 프로그램에 붙어있다.이 프로그램은 키워드를 물어보고 사용 가능한 제목 목록에서 키워드를 검색하는 명령 줄 프로그램이라고 가정한다. 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에 지시하십시오. 다음은 -w 또는 --word 플래그가있는 'word'인수와 -p 또는 --points 플래그가있는 '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

는 당신이 add_argument() 방법을 사용하여 객체에 인수를 추가 할 수 있습니다, 당신이 먼저 ArgumentParser 객체를 선언 할 것 argparse을 사용합니다. 이 후 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

내가 다른 explainations 이상이 훨씬 더 이해에 액세스 할 수 있도록 명령 줄에서 실행하려면 그렇게 할 것 나는 다른 곳을 보았습니다. 그러나 어떻게 이것을 point와 word의 결과를 결합한 _main_의 인스턴스로 실행합니까? – KRose