2017-11-10 15 views
1

私はSpyderを使用しているPythonユーザーです。私はメモ帳からデータ(つぶやき)を変換し、変換されたデータを他のメモ帳に出したい。そのコードはそうです。それは、このような{created at: date, user_name, unicode..} -> user_name, dataPythonで必要なデータを取得できません

try: 
    import json 
except ImportError: 
    import simplejson as json 

tweets_filename = 'C:/Users/siri_0.txt' #unconverted data 
tweets_file = open(tweets_filename, "r") 

for line in tweets_file: 
    try: 
     tweet = json.loads(line.strip()) 
     if 'text' in tweet: 
      print (tweet['id']) 
      print (tweet['created_at']) 
      print (tweet['text']) 
      print (tweet['user']['id']) 
      print (tweet['user']['name']) 
      print (tweet['user']['screen_name']) 
      hashtags = [] 
      for hashtag in tweet['entities']['hashtags']: 
       hashtags.append(hashtag['text']) 
      print(hashtags) 

      output = "C:/Users/fn_siri.txt" 
      #I want to put the converted data here. 
      out_file = open(output, 'a') 
      out_file.write(line) 
      out_file.close() 

    except: 
     continue 

残念ながら、C:/Users/fn_siri.txtのみ「未変換データ」を含めることができるような単純なデータを作成します。変換されたデータを含むコードを変更するにはどうすればよいですか?

+0

out_file.write(tweet['user']['name'] + "," + tweet['text'] + "\n")

あなたはそれがデータのすべての行の後に新しい行を持っていることを確認するために最後に\nを必要とします'を' tweets_file'に入れて、 'print'ingをたくさんして元の' line'値をあなたの出力ファイルに保存してください。あなたの情報を画面に印刷するということを、あなたは変数にテキスト文字列として保存し、それらをファイルに保存しなければなりません。あなたは助けが必要な場所ですか? – offeltoffel

+0

私はそれを解決しました。ありがとう:) –

答えて

1

あなたの未変換入力された出力ファイルにlineを書き出すのではなく、唯一の必要なデータを書き込んでいます。

したがって、ユーザー名の後にカンマと、それに続く、たとえば、テキスト、あなたは交換する必要があなたのout_file.write(line)と:あなたはすべての `の行を反復処理している

+0

ありがとう。私はあまりにも明確に欲しいデータを持っています:) –

1
try: 
    import json 
except ImportError: 
    import simplejson as json 

tweets_filename = 'C:/Users/siri_0.txt' #unconverted data 
tweets_file = open(tweets_filename, "r") 
for line in tweets_file: 
    try: 
     tweet = json.loads(line.strip()) 
     out_file = open(output, 'a') 
     if 'text' in tweet: 
      print (tweet['id'],) 
      print (tweet['created_at']) 
      print (tweet['text']) 
      print (tweet['user']['id']) 
      print (tweet['user']['name']) 
      print (tweet['user']['screen_name']) 
      hashtags = [] 
      for hashtag in tweet['entities']['hashtags']: 
       hashtags.append(hashtag['text']) 
      output = "C:/Users/fn_siri.txt" 
      print(hashtags,file=out_file) 
      #I am assuming the converted data you want to write to out_file is hashtags 
      #out_file.write(line)# why are you writing old data here ... 
      out_file.close() 
    except: 
     continue 
+0

あなたの助けをありがとう:D –

関連する問題