Skip to main content
 首页 » 编程设计

python之统一码编码错误 : 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128)

2024年10月25日15开发

我是 Python 的新手,必须构建一个应用程序才能从 Twitter 获取历史数据。我可以在我的控制台中看到推文以及我需要的所有信息! 但我现在遇到的问题是,我需要将这些信息写入.csv文件,但在运行代码时遇到以下错误: “UnicodeEncodeError:'ascii' 编解码器无法对位置 0 中的字符 u'\xe4' 进行编码:序号不在范围 (128) 内”。我知道问题在于我收集的推文是用瑞典语写的,所以经常使用字母 "ÅÄÖ"。 谁能帮我解决这个问题,或者对我应该从哪里开始寻找解决方案有任何指示?

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
 
 
from TwitterSearch import * 
import csv 
 
import codecs 
 
 
 
 
 
try: 
    tuo = TwitterUserOrder('Vismaspcs') # create a TwitterUserOrder 
 
 
    ts = TwitterSearch( 
        consumer_key = '', 
        consumer_secret = '', 
        access_token = '', 
        access_token_secret = '' 
    ) 
 
    # start asking Twitter about the timeline 
    for tweet in ts.search_tweets_iterable(tuo): 
        print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text']) ) 
        print (tweet['created_at'],tweet['favorite_count'],tweet ['retweet_count']) 
 
 
 
 
    with open('visma.csv','w') as fout: 
        writer=csv.writer(fout)     
        writer.writerows([tweet['user']['screen_name'],tweet['text'],tweet['created_at'],tweet['favorite_count'],tweet['retweet_count']]) 
 
 
 
except TwitterSearchException as e: # catch all those ugly errors 
    print(e) 

请您参考如下方法:

csv 模块无法处理 python2 中的 unicode:

Note This version of the csv module doesn't support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

你可以使用tweet['user']['screen_name'].encode("utf-8")...