2017-10-15 13 views
1

jsonファイルをcsvファイルに変換しようとしています。 jsonファイルはtweepyから来ました。は、Pythonでcsvファイルを書き込めません

import json 
import csv 

fo = open('Sclass.json', 'r') 
fw = open('Hasil_Tweets.csv', 'a') 

for line in fo: 
     try: 
       tweet = json.loads(line) 
       fw.write(tweet['id'],tweet['timestamp_ms'],tweet['user']['name'],tweet['user']['statuses_count'],tweet['user']['friends_count'],tweet['user']['followers_count'],tweet['place']['bounding_box']['coordinates'],tweet['text']+"\n") 
     except: 
       continue 

ただし、印刷すると機能します。 と書くときは、ちょうどfw.write(tweet['text'])と書いてあります。

おかげ

屋ああ、私はどちらのpythonとtweepy上のnoob。しかし、私の本能は、この問題はjsonファイルと関連していると言っています。私の英語には申し訳ありません。

{ 
    "created_at": "Wed Oct 11 08:36:21 +0000 2017", 
    "id": 918032510927355904, 
    "id_str": "918032510927355904", 
    "text": "@irfanzayo @puisisi @tasyak Lo tuh kebiasaan overthinking \ud83d\ude24", 
    "display_text_range": [ 
     28, 
     59 
    ], 
    "source": "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>", 
    "truncated": false, 
    "in_reply_to_status_id": 918032029094047746, 
    "in_reply_to_status_id_str": "918032029094047746", 
    "in_reply_to_user_id": 60049976, 
    "in_reply_to_user_id_str": "60049976", 
    "in_reply_to_screen_name": "irfanzayo", 
    "user": { 
     "id": 59980455, 
     "id_str": "59980455", 
     "name": "Mutiara Sisyanni D", 
     "screen_name": "MutiaraSisyanni", 
     "location": "Jakarta, Indonesia", 
     "url": "http://mutiarasyn.wixsite.com/mutiarasisyanni", 
     "description": null, 
     "translator_type": "none", 
     "protected": false, 
     "verified": false, 
     "followers_count": 354, 
     "friends_count": 237, 
     "listed_count": 1, 
     "favourites_count": 326, 
     "statuses_count": 6507, 
     "created_at": "Sat Jul 25 04:31:47 +0000 2009", 
     "utc_offset": 25200, 
     "time_zone": "Jakarta", 
     "geo_enabled": true, 
     "lang": "en", 
     "contributors_enabled": false, 
     "is_translator": false, 
     "profile_background_color": "FA8C9E", 
     "profile_background_image_url": "http://abs.twimg.com/images/themes/theme5/bg.gif", 
     "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme5/bg.gif", 
     "profile_background_tile": false, 
     "profile_link_color": "FF8A94", 
     "profile_sidebar_border_color": "FFFFFF", 
     "profile_sidebar_fill_color": "99CC33", 
     "profile_text_color": "3E4415", 
     "profile_use_background_image": false, 
     "profile_image_url": "http://pbs.twimg.com/profile_images/486497248293826560/FANdzhL9_normal.jpeg", 
     "profile_image_url_https": "https://pbs.twimg.com/profile_images/486497248293826560/FANdzhL9_normal.jpeg", 
     "profile_banner_url": "https://pbs.twimg.com/profile_banners/59980455/1404826066", 
     "default_profile": false, 
     "default_profile_image": false, 
     "following": null, 
     "follow_request_sent": null, 
     "notifications": null 
    }, 
    "geo": null, 
    "coordinates": null, 
    "place": { 
     "id": "66555622726ab358", 
     "url": "https://api.twitter.com/1.1/geo/id/66555622726ab358.json", 
     "place_type": "city", 
     "name": "Setia Budi", 
     "full_name": "Setia Budi, Indonesia", 
     "country_code": "ID", 
     "country": "Indonesia", 
     "bounding_box": { 
      "type": "Polygon", 
      "coordinates": [ 
       [ 
        [ 
         106.817351, 
         -6.24152 
        ], 
        [ 
         106.817351, 
         -6.201177 
        ], 
        [ 
         106.852353, 
         -6.201177 
        ], 
        [ 
         106.852353, 
         -6.24152 
        ] 
       ] 
      ] 
     }, 
     "attributes": {} 
    }, 
    "contributors": null, 
    "is_quote_status": false, 
    "quote_count": 0, 
    "reply_count": 0, 
    "retweet_count": 0, 
    "favorite_count": 0, 
    "entities": { 
     "hashtags": [], 
     "urls": [], 
     "user_mentions": [ 
      { 
       "screen_name": "irfanzayo", 
       "name": "irfan zayanto", 
       "id": 60049976, 
       "id_str": "60049976", 
       "indices": [ 
        0, 
        10 
       ] 
      }, 
      { 
       "screen_name": "puisisi", 
       "name": "Puisi Pancara", 
       "id": 32809069, 
       "id_str": "32809069", 
       "indices": [ 
        11, 
        19 
       ] 
      }, 
      { 
       "screen_name": "tasyak", 
       "name": "Tasya Kurnia", 
       "id": 41986880, 
       "id_str": "41986880", 
       "indices": [ 
        20, 
        27 
       ] 
      } 
     ], 
     "symbols": [] 
    }, 
    "favorited": false, 
    "retweeted": false, 
    "filter_level": "low", 
    "lang": "in", 
    "timestamp_ms": "1507710981481" 
} 

別のエラー

Traceback (most recent call last): File "C:\Users\User\Desktop\fase 1-20170930T062552Z-001\transformCSV.py", line 7, in tweet = json.loads(line) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\json__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

Traceback (most recent call last): 
    File "C:\Users\Tanabata\Desktop\Putang ina mo\spli.py", line 8, in <module> 
    tweet = json.load(fo) 
    File "C:\Users\Tanabata\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load 
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) 
    File "C:\Users\Tanabata\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads 
    return _default_decoder.decode(s) 
    File "C:\Users\Tanabata\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 342, in decode 
    raise JSONDecodeError("Extra data", s, end) 
json.decoder.JSONDecodeError: Extra data: line 3 column 1 (char 2893) 

JSONファイルitselft:http://www.mediafire.com/file/l3rzzbe0nbu1nlu/Sclass.json

答えて

0

あなたはcsvを使用していない これは、JSONファイルも自己です。あなたはJSON-ライン・ファイルが、単一のJSONデータセットを使用してファイルを持っていない、それはそう、あなたの2番目の質問について

import json 
import csv 

with open('Sclass.json', 'r') as fo, open('Hasil_Tweets.csv', 'a') as fw: 
    writer = csv.writer(fw) 
    for line in fo: 
     tweet = json.loads(line) 
     writer.writerow([tweet['id'],tweet['timestamp_ms'],tweet['user']['name'], 
      tweet['user']['statuses_count'],tweet['user']['friends_count'], 
      tweet['user']['followers_count'], 
      tweet['place']['bounding_box']['coordinates'],tweet['text']]) 

:あなたはwriterを作成する必要があります。すぐにテーブル(CSVている1)思考パンダ(私の意見)を使用して作業しているよう

with open('Sclass.json', 'r') as fo: 
    tweet = json.load(fo) 

with open('Hasil_Tweets.csv', 'a') as fw 
    writer = csv.writer(fw) 
    writer.writerow([tweet['id'],tweet['timestamp_ms'],tweet['user']['name'], 
     tweet['user']['statuses_count'],tweet['user']['friends_count'], 
     tweet['user']['followers_count'], 
     tweet['place']['bounding_box']['coordinates'],tweet['text']]) 
+0

ありがとうございます。しかし、私は他のerorrを持っています:AttributeError: '_csv.writer'オブジェクトには属性 'write'がありません – Tanabata

+0

申し訳ありません、 'writerow'です。回答が修正されました。 – Daniel

+0

あなたに感謝しますが、他のerorr:writerow()はちょうど1つの引数(8が与えられます)を受け取ります。 – Tanabata

0

:だから行ずつ読みすることで、全体としてファイルを読み込む必要があり、間違っています。

この場合、pandas json_normalizeを使用してjsonファイルを解釈できます。

import json 
from pandas.io.json import json_normalize 

with open("Sclass.json.json") as f: 
    df = json_normalize(json.load(f)) 

cols = ["id","timestamp_ms","user.name", 
     "user.statuses_count","user.friends_count","user.followers_count", 
     "place.bounding_box.coordinates","text"] 

df[cols].to_csv("Hasil_Tweets.csv",sep=",",index=False) # outputs to csv 

パンダは、そのうちの一つは、HTMLテーブルであること、多くの出力オプションが付属しています。私はoututを表示するためにこれを使用します。

print(df[cols].to_html(index=False)) # outputs to html to show result 

出力

<table border="1" class="dataframe"> 
 
    <thead> 
 
    <tr style="text-align: right;"> 
 
     <th>id</th> 
 
     <th>timestamp_ms</th> 
 
     <th>user.name</th> 
 
     <th>user.statuses_count</th> 
 
     <th>user.friends_count</th> 
 
     <th>user.followers_count</th> 
 
     <th>place.bounding_box.coordinates</th> 
 
     <th>text</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td>918032510927355904</td> 
 
     <td>1507710981481</td> 
 
     <td>Mutiara Sisyanni D</td> 
 
     <td>6507</td> 
 
     <td>237</td> 
 
     <td>354</td> 
 
     <td>[[[106.817351, -6.24152], [106.817351, -6.2011...</td> 
 
     <td>@irfanzayo @puisisi @tasyak Lo tuh kebiasaan o...</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

+0

ありがとうございます。しかし、ここでいくつかの問題が発生します。1. JSONDecodeError( "Extra data"、s、end)2.json.decoder.JSONDecodeError:余分なデータ:3行目の1列目(char 2893)は何ですか?あなたがデータを抽出することができたときと私>していないとき。< – Tanabata

+0

@ Tanabataうーん。あなたが投稿したテキストを取り、同じ名前のjsonファイルを作成した。おそらくもっとデータがありますか?私は通常何かが間違っているかどうかを確認するためにjsonlint.comを使います。 –

+0

私はjsonを検証しようとしましたが、その結果は正しくなく、他のjsonファイルを試しています= https://nocodewebscraping.com/twitter-json-examples/ witchにはjsonファイルがあります。全く同じエラーです:JSONDecodeError( "Extra data"、s、end) json.decoder.JSONDecodeError:余分なデータ:行89列2(char 3438)違う行、欄、およびグラフです。オハイオ州私は上記の質問に私のjsonファイルを投稿します。ご相談いただきありがとうございます – Tanabata

0

私は別の答えとしてこれを追加しています。

あなたが共有した* .jsonは、実際には複数のjson文字列を含む大きなファイルですが、2行ごとです。どのようにあなたは私にはわからないが、あなたはこれを使用してそれを読むことができ、最初からこのファイルを得た:しかし、データフレームには、この構造を読むとき、あなたはそれが本当に明確な構造ではないことがわかります

import json 
import pandas as pd 

with open("Sclass.json") as f: 
    data = [json.loads(row.strip()) for row in f.readlines()[0::2]] 

pd.DataFrame(data) 

結論:あなたの問題は完全に別のものです。

+0

ありがとうございます。だからjsonファイルはうまく構造化されたサー?あなたは私のストリームリスナーを修正して、私が適切なjsonファイルまたはCSVファイルを取得できるようにしても構わないのですか?これは私のcondeです:def on_data(self、data): try: open( 'tescsv.json'、 ' (eとBaseException除くデータ) trueを返します : プリント( "エラーon_data:%s" は%strの(e)の f.write:) trueを返します デフON_ERROR(自己、ステータス)をf ') : print(ステータス) return True – Tanabata

関連する問題