2016-07-10 2 views
0

이전 게시물이 API 토큰을 가지고있을 때 다시 게시합니다. 나는 웹 사이트에서 데이터를 긁어 오전 : 다음은 코드입니다 :UnicodeDecodeError : 'ascii'코덱은 위치 19에서 0xc3 바이트를 디코딩 할 수 없습니다. 서수가 범위 내에 없습니다 (128)

reload(sys) 
sys.setdefaultencoding('utf-8-sig') 

def __unicode__(self): 
    return unicode(self.some_field) or u'' 
def daterange(start_date, end_date): 
    for n in range(int ((end_date - start_date).days)): 
     yield start_date + timedelta(n+1) 
#def is_ascii(s): 
    #return all(ord(c) < 128 for c in s) 
date='' 
min_date='' 
max_date='' 
if sys.argv[1] == 'today': 
    min_date = datetime.today() - timedelta(1) 
    max_date = datetime.today() 
elif sys.argv[1] == 'yesterday': 
    min_date = datetime.today() - timedelta(2) 
    max_date = datetime.today() - timedelta(1) 
else: 
    min_date = datetime.strptime(sys.argv[1], "%Y-%m-%d") - timedelta(1) 
    max_date = datetime.strptime(sys.argv[2], "%Y-%m-%d") 
siteIDs = [37] 
for id in siteIDs: 
    for date in daterange(min_date, max_date): 
     response_data = {} 
     url = 'http://survey.modul.ac.at/piwikAnalytics/?module=API&method=Live.getLastVisitsDetails&idSite=' + str(id) + '&format=csv&token_auth=' + token_auth + '&period=day&date=' + date.strftime('%Y-%m-%d') + '&filter_limit=2000' 
     try: 
      response=requests.get(url,timeout=100) 
      response_url=response.url 
      response_data=urllib.urlopen(url) 

     except (requests.exceptions.Timeout,requests.exceptions.RequestException,requests.exceptions.HTTPError,requests.exceptions.ConnectionError,socket.error) as e : 
      response_data="error" 
     with codecs.open('raw_csv/piwik_'+ str(id) + '_' + date.strftime('%Y-%m-%d')+ '.csv', 'wb',encoding='utf-8-sig') as fp: 
       fp.write(response.text) 

출력 열에서 'idSite' '  idSite'로 표시되고있다. 나는 다음과 같은 코드를 제거하려고 :

import pandas as pd 

df = pd.read_csv("piwik_37_2016-07-08.csv", dtype = "unicode", encoding="utf-8-sig") 
df.to_csv("abc.csv") 

하지만 문자열에서 모든 비 ASCII 문자를 제거하기 위해 위에서 언급 한 유니 코드 오류를

+0

가능한 중복 http://stackoverflow.com/questions/12556839/is-there-an-easy- 길을 만들다 - 유니코 de-work-in-python) –

+0

읽기 작업을 수행 할 때 유니 코드 값을 얻습니다. 이러한 유니 코드 문자는 csv 파일에 쓰기 전에 바이트로 변환해야합니다. 그래서, 당신은 이것을해야합니다 :'df.to_csv ("abc.csv", encoding = 'utf-8')' –

답변

0

한 무력 방법을 얻고있다 :

import re 
# substitute sequence of non-ASCII characters with single space 
str = re.sub(r'[^\x00-\x7F]+',' ', str) 
귀하의 경우에 도움이

희망

[파이썬에서 유니 코드를 작동하게 할 수있는 간단한 방법이 있을까요?] (의
관련 문제