繁体   English   中英

Python Utf-8写入CSV

[英]Python Utf-8 writing into CSV

我无法将已经编码的数据保存到CSV中。 之后我可以解码CSV文件,但我宁愿先进行所有数据清理。 我设法只保存文本,但是当添加时间戳时,这是不可能的。

我做错了什么? 我读到如果srt().encode()无法正常工作,应该尝试使用.join代替,但还是没有

错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) 

码:

def on_data(self, data):
    try:
        #print data
        tweet = data.split(',"text":"')[1].split('","source')[0]

        x = tweet.encode('utf-8')
        y = x.decode('unicode-escape')
        print y

        saveThis = y
        #saveThis = str(time.time())+'::' + tweet.decode('ascii', 'ignore')
        #saveThis = u' '.join((time.time()+'::'+tweet)).encode('utf-8')

        saveFile = open('twitDB.csv', 'a')
        saveFile.write(saveThis)
        saveFile.write('\n')
        saveFile.close()
        return True
    except BaseException, e:
        print 'fail on data,', str(e)
        time.sleep(5) 
def on_error(self, status):
    print status

首先,请确保使用json模块正确处理JSON数据。

接下来,不要捕获BaseException ,您没有理由在这里捕获内存错误或键盘中断。 而是捕获更具体的异常。

接下来,在写入之前对数据进行编码:

def on_data(self, data):
    try:
        tweet = json.loads(data)['text']
    except (ValueError, KeyError), e:
        # Not JSON or no text key
        print 'fail on data {}'.format(data)
        return

   with open('twitDB.csv', 'a') as save_file:
        save_file.write(tweet.encode('utf8') + '\n')
        return True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM