2017-11-30 1 views
0

안녕하세요, 나는 성공적으로 파이썬에서 분할 기능을 사용하여 문제가 있습니다. 크롤러를 사용하여 일부 트윗을 수집했으며 각 트윗의 일부분을 다른 .json 파일 (특히 ID 및 # (해시 태그))로 분할해야합니다. 나는 성공하지 못한 split 함수를 사용하고있다. 나는 잘못하고있다? 나는 "ID"및 "텍스트"후 어떤 다른 .json 파일로 저장할
이 텍스트는 다음과 같습니다어떻게 파이썬에서 분할 기능을 사용하여 텍스트의 일부를 분할하고 다른 파일에 저장할 수 있습니까?

{ "created_at": "20 16시 35분 36초 0000 2017 금 시월" "ID"921414607302025216 "ID_STR": "921414607302025216", "텍스트": "@ IdrisAhmed16 loooooool 내가 indirecting 있다고 말했다 누가 당신은 내가 당신이 명령 줄에 파이썬을 실험한다고 생각

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 변수가 정상 파이썬 개체입니다 : 당신이 원하는 무엇

는 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'] 
관련 문제