UnicodeDecodeError:'ascii'编解码器无法解码位置19的字节0xc3:序数不在范围内(128)

时间:2016-07-10 01:08:21

标签: python python-2.7 pandas unicode

在上一篇文章中再次发布了API令牌。我正在从网站上抓取数据:这是代码:

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")

但是我得到了上面提到的Unicode错误

1 个答案:

答案 0 :(得分:0)

从字符串中删除所有非ASCII字符的一种强制方法是:

import re
# substitute sequence of non-ASCII characters with single space
str = re.sub(r'[^\x00-\x7F]+',' ', str)

希望在你的情况下有所帮助