2014-05-13 3 views
2

일부 JSON Twitter 데이터를 수집하고 CSV 파일의 개별 열로 일부 특정 필드를 출력하는 간단한 코드가 있습니다. 내 문제는 내가 UTF-8로 출력을 인코딩하는 적절한 방법을 찾아 낼 수 없다는 것이다. 아래는 회원의 도움을 받아 내가 가졌던 가장 가까운 것입니다.하지만 여전히 여전히 올바르게 실행되지 않고 트윗 텍스트 필드의 고유 한 문자 때문에 실패합니다. 문서에서CSV에 쓸 때 UTF-8 인코딩하기

import json 
import sys 
import csv 
import codecs 

def main(): 

    writer = csv.writer(codecs.getwriter("utf-8")(sys.stdout), delimiter="\t") 
    for line in sys.stdin: 
     line = line.strip() 

     data = [] 

     try: 
      data.append(json.loads(line)) 
     except ValueError as detail: 
      continue 

     for tweet in data: 

      ## deletes any rate limited data 
      if tweet.has_key('limit'): 
       pass 

      else: 
       writer.writerow([ 
       tweet['id_str'], 
       tweet['user']['screen_name'], 
       tweet['text'] 
       ]) 

if __name__ == '__main__': 
    main() 

답변

2

: https://docs.python.org/2/howto/unicode.html

a = "string" 

encodedstring = a.encode('utf-8') 

문제가 해결되지 않으면 : 저도 같은 문제가 있었다

Python DictWriter writing UTF-8 encoded CSV files

+0

감사합니다. @ user2100799 -'.encode ('utf-8')의 모든 변형을 시도해 보았습니다. 설명서를 읽었지만 여전히 제대로 작동하지 않습니다. CSV 모듈. 다른 제안? –

+0

여기에서 시도하십시오. http://stackoverflow.com/questions/5838605/python-dictwriter-writing-utf-8-encoded-csv-files – 1478963

0

. 나는 트위터 firehose에서 많은 양의 데이터를 가지고 있으므로 가능한 모든 합병증이 발생합니다 (그리고 발생했습니다)!

제외/시도를 사용하여 다음과 같이 내가 그것을 해결 한 다음 DICT 값이 문자열 인 경우

: if isinstance(value,basestring) 나는 바로 그것을 인코딩하려고합니다. 문자열이 아니면 문자열로 만든 다음 인코딩합니다.

만약 이것이 실패하면, 어떤 조커가 내 스크립트를 엉망으로 만들기 위해 홀수 기호를 트위터하기 때문입니다.

import csv 

def export_to_csv(list_of_tweet_dicts,export_name="flat_twitter_output.csv"): 

    utf8_flat_tweets=[] 
    keys = [] 

    for tweet in list_of_tweet_dicts: 
     tmp_tweet = tweet 
     for key,value in tweet.iteritems(): 
      if key not in keys: keys.append(key) 

      # convert fields to utf-8 if text 
      try: 
       if isinstance(value,basestring): 
        tmp_tweet[key] = value.encode('utf-8') 
       else: 
        tmp_tweet[key] = str(value).encode('utf-8') 
      except: 
       if isinstance(value,basestring): 
        tmp_tweet[key] = value.decode('utf-8').encode('utf-8') 
       else: 
        tmp_tweet[key] = str(value.decode('utf-8')).encode('utf-8') 

     utf8_flat_tweets.append(tmp_tweet) 
     del tmp_tweet 

    list_of_tweet_dicts = utf8_flat_tweets 
    del utf8_flat_tweets 

    with open(export_name, 'w') as f: 
     dict_writer = csv.DictWriter(f, fieldnames=keys,quoting=csv.QUOTE_ALL) 
     dict_writer.writeheader() 
     dict_writer.writerows(list_of_tweet_dicts) 

    print "exported tweets to '"+export_name+"'" 

    return list_of_tweet_dicts 

희망 : 이런 경우, 먼저 내가 아닌 문자열

value.decode('utf-8').encode('utf-8')에 대한 문자열 및 재 인코딩으로 만들이있는 이동을 가지고, 다시 인코딩 문자열과 디코딩을위한 value.decode('utf-8').encode('utf-8')을 다음 디코딩 너를 돕는거야.

관련 문제