2017-11-30 4 views
0

こんにちは私はPythonで分割関数を使用して成功していない問題があります。私はクローラを使っていくつかのつぶやきを集めました。それぞれのつぶやきの一部を別の.jsonファイル、特にIDと#(ハッシュタグ)に分割する必要があります。私は間違って何をしているの成功と分割関数を使用していますか?私は「ID」の後には何か違う.jsonファイルに保存すると、「テキスト」
は、テキストは次のようになります。どのように私は、Pythonで分割関数を使用してテキストの一部を分割し、別のファイルに保存できますか?

{「のcreated_at」:「金10月20日午後四時35分36秒0000 2017」 、 "ID":921414607302025216、 "id_str": "921414607302025216"、 "テキスト": "@ IdrisAhmed16 loooooool私がindirectingたという人は、あなたが私はあなたがコマンドラインでPythonを試してみるべきだと思い

def on_data(self, data): 
    try: 
     #print data 
     with open('Bologna_streams.json', 'r') as f: 
      for line in f: 

       tweet = data.spit(',"text":"')[1].split('",""source"')[0] 
       print (tweet) 

       saveThis = str(time.time()) + '::' +tweet 

       saveFile = open('Bologna_text_preprocessing.json', 'w') 
       json.dump(data) 
       saveFile.write(saveThis) 
       saveFile.write(tweet) 
       saveFile.write('\n') 
       saveFile.close() 
       f.close() 
     return True 
    except BaseException as e: 
     print("Error on_data: %s" % str(e)) 
     time.sleep(5) 

def on_error(self, status): 
    print (status) 
+0

はあなたがされているテキストの例を与えることができます目的はすべてのハッシュタグを検索している場合

しかし、あなたは正規表現を使用する方がよいでしょう分割しようとしています –

+0

@NickChapmanの意味は次のとおりです。分割しようとしているテキストの例で**質問**を更新できますか? – quamrana

+0

確かです。 –

答えて

1

を??対話形式でも小さなスクリプトでもよい。

これを考慮する:

コンソールに出力します

['{"created_at"', '"Fri Oct 20 16', '35', '36 +0000 2017","id"', '921414607302025216,"id_str"', '"921414607302025216","text"', '"@IdrisAhmed16 learn #python"}'] 

それとも、新しいライン上の各分割画面を印刷するには:

この印刷されます
print("splits:\n") 
for item in text.split(":"): 
    print(item) 
print("\n---") 

:で

splits: 

{"created_at" 
"Fri Oct 20 16 
35 
36 +0000 2017","id" 
921414607302025216,"id_str" 
"921414607302025216","text" 
"@IdrisAhmed16 #learn python"} 

--- 

を他の言葉では、splitはこれを行う必要があります:すべて":"を見つけ、thオセ文字。

import json 

parsed = json.loads(text) 
print("parsed:", parsed) 

parsed変数は、通常のPythonオブジェクトである:あなたが何をしたいか

はJSONをパースです。結果:

parsed: { 
    'created_at': 'Fri Oct 20 16:35:36 +0000 2017', 
    'id': 921414607302025216, 
    'id_str': '921414607302025216', 
    'text': '@IdrisAhmed16 learn #python' 
} 

今、あなたはtextアイテムを取得し、それを分割するなど、データ上で操作を行うことができます。

import re 
hashtag_pattern = re.compile('#(\w+)') 
matches = hashtag_pattern.findall(parsed['text']) 
print("All hashtags in tweet:", matches) 

print("Another example:", hashtag_pattern.findall("ok #learn #python #stackoverflow!")) 

結果:

All hashtags in tweet: ['python'] 
Another example: ['learn', 'python', 'stackoverflow'] 
関連する問題