2017-01-06 6 views
0

JSON 파일을 데이터 프레임에 맞추려고합니다.JSON 파일을 pandas 데이터 프레임에 맞추는 중 오류가 발생했습니다.

fname = 'python.json' 
with open(fname, 'r') as f, open('sentiment.json', 'w') as s: 
for line in f: 
    tweet = json.loads(line) 
    # Create a list with all the terms 
    tweet_words = tweet['text'] 
    output = subprocess.check_output(['curl', '-d', "text=" + tweet_words.encode('utf-8'), 'http://text-processing.com/api/sentiment/']) 
    s.write(output+"\n") 

그것은 기록하는 text-processing.com의 API에서 요청 'sentiment.json'출력에 : 내 현재 도청 코드는 다음과 같은 방법을 통해 JSON 파일을 만듭니다. 그때 사용하여 JSON을로드 :

def load_json(file, skip): 
with open(file, 'r') as f: 
    read = f.readlines() 
    json_data = (json.loads(line) for i, line in enumerate(read) if i%skip==0) 
return json_data 

을 그리고 사용 dataframe를 구성 :

sentiment_df = load_json('sentiments.json', 1) 

data = {'positive': [], 'negative': [], 'neutral': []} 
for s in sentiment_df: 
     data['positive'].append(s['probability']['pos']) 
     data['negative'].append(s['probability']['neg']) 
     data['neutral'].append(s['probability']['neutral']) 

df = pd.DataFrame(data) 

오류 :에 ValueError : 없음 JSON 객체가 내가 몇 가지 관련 질문을 통해 찾아

를 디코딩 할 수 없었다 WoodrowShigeru의 답변 here을 기반으로, 첫 번째 코드 블록에서 'utf-8'로의 인코딩과 관련이 있다고 생각됩니다.

누구든지 좋은 수정 사항을 알고 있습니까? 아니면 적어도 몇 가지 지시 사항을 제공합니까? 고마워요!

편집 한

Screen of 'sentiment.json'

답변

0

귀하의 스크린 샷은 모든 쉼표로 구분 된 개별 항목을 보유해야 컨테이너와 같은 유효한 JSON 없습니다. 그러나 문제는 명령 줄 호출이 문자열 output을 반환하고 텍스트 파일에 쓰는 것입니다. json.dumps()으로 json 파일에 덤프되는 사전 목록을 작성해야합니다.

첫 번째 텍스트 파일을 읽는 동안 명령 줄 문자열을 사전에 캐스팅하여 ast.literal_eval()으로 바꾸는 것이 좋습니다. 그런 다음 목록에 각 사전을 추가 : 거기에서

import ast 

fname = 'python.json' 
dictList = [] 
with open(fname, 'r') as f, open('sentiment.json', 'w') as s: 
    for line in f: 
     tweet = json.loads(line) 
     # Create a list with all the terms 
     tweet_words = tweet['text'] 
     output = subprocess.check_output(['curl', '-d', "text=" + tweet_words.encode('utf-8'), 
             'http://text-processing.com/api/sentiment/']) 
     # CONVERT STRING TO DICT AND APPEND TO LIST 
     dictList.append(ast.literal_eval(output)) 

    # CONVERT TO JSON AND WRITE TO FILE 
    s.write(json.dumps(dictList, indent=4)) 

json_normalize와 팬더 dataframe에 JSON 파일을 읽습니다.

Sentiment json file

import json 
import pandas as pd 

with open('sentiment.json') as f: 
    data = json.load(f) 

df = pd.io.json.json_normalize(data) 
df.columns = [c.replace('probability.', '') for c in df.columns] 
print(df) 

#  label  neg neutral  pos 
# 0  pos 0.003228 0.204509 0.571945 
# 1  pos 0.053094 0.097317 0.912760 
# 2  pos 0.954958 0.163341 0.917178 
# 3  pos 0.784391 0.646188 0.955281 
# 4  pos 0.203419 0.050908 0.490738 
# 5  neg 0.122760 0.705633 0.219701 
# 6  neg 0.961012 0.923886 0.335999 
# 7  neg 0.368639 0.562720 0.124530 
# 8  neg 0.566386 0.802366 0.825956 
# 9  neg 0.115536 0.512605 0.784626 
# 10 neutral 0.202092 0.741778 0.567957 
# 11 neutral 0.837179 0.051033 0.509777 
# 12 neutral 0.333542 0.085449 0.610222 
# 13 neutral 0.798188 0.248258 0.218591 
# 14 neutral 0.873109 0.469737 0.005178 
# 15  pos 0.916112 0.313960 0.750118 
# 16  neg 0.810080 0.852236 0.212373 
# 17 neutral 0.748280 0.039534 0.323145 
# 18  pos 0.274492 0.461644 0.984955 
# 19  neg 0.063772 0.793171 0.631172 
: 다음 예제 데이터를 사용