2016-06-16 3 views
0

텍스트 파일 (열에 저장 됨)에서 값을 읽고 URL 매개 변수에 전달하려고합니다. 작성자 ID는 고유하며 텍스트 파일의 ID 값을 반복하고 싶습니다.텍스트 파일에서 값을 읽고 URL 매개 변수로 전달하는 방법

내용에 대한 데이터 유형은 목록이며, 다음과 같습니다 여기

['7202106849\n', '7201570041\n', ....] 

내가 지금까지 작성한 코드 (I가 완료되지 알고 좀 반복 도움 저자 ID를 통과 필요하다 URL 매개 변수로 컨텐츠)에서 다음과 같이

with open('collab_id_2008.txt') as f: 
content = f.readlines() 

url = "https://api.elsevier.com/content/author/author_id/6602198520?view=metrics" 
resp = requests.get(url, headers={'Accept':'application/json','X-ELS-APIKey': 'xxxxxxx', 'X-ELS-Insttoken': 'xxxxxxxx'}) 
print json.dumps(resp.json(), sort_keys=True, indent=4, separators=(',', ': ')) 
+0

당신이 필요로하는'일부 help'은 무엇입니까? –

+0

현재 API는 단일 작성자 ID에 대한 정보 만 가져올 수 있습니다. 저자의 ID를 콘텐츠의 url 매개 변수로 전달하여 텍스트 파일의 모든 작성자에 대한 통계를 얻을 수 있습니다. – anandg112

답변

3

뭔가 당신은 가야한다 :

import requests 
import json 


with open('collab_id_2008.txt') as f_input: 
    for id in f_input: 
     url = "https://api.elsevier.com/content/author/author_id/{}?view=metrics".format(id.strip()) 
     resp = requests.get(url, headers={'Accept':'application/json','X-ELS-APIKey': 'xxxxxxx', 'X-ELS-Insttoken': 'xxxxxxxx'}) 
     print json.dumps(resp.json(), sort_keys=True, indent=4, separators=(',', ': ')) 

입력 파일을 읽고 URL에 id을 입력하십시오. 파일로 출력하려면


, 그것은 정말 여기, 당신이 필요로하는 포맷에 따라 하나의 예입니다

with open('collab_id_2008.txt') as f_input, open('output.txt', 'w') as f_output: 
    for id in f_input: 
     url = "https://api.elsevier.com/content/author/author_id/{}?view=metrics".format(id.strip()) 
     resp = requests.get(url, headers={'Accept':'application/json','X-ELS-APIKey': 'xxxxxxx', 'X-ELS-Insttoken': 'xxxxxxxx'}) 
     print json.dumps(resp.json(), sort_keys=True, indent=4, separators=(',', ': ')) 
     json.dump(resp.json(), f_output) 
+0

고마워요! 이것은 잘 작동합니다. 결과를 출력하는 대신 CSV 또는 json 파일로 출력을 작성하고 싶습니다. 어떤 팁? – anandg112

+0

api 키를 가지고 있지 않습니다. 출력을 볼 수 없지만'json.dump()'를 사용하여 json을 파일에 쓸 수 있습니다. 예제를 추가했습니다. –

관련 문제