【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) with python [duplicate]UnicodeEncodeError:'ascii'编解码器无法编码位置0-2中的字符:序数不在范围内(128)与python [重复]
【发布时间】:2020-07-26 18:03:11
【问题描述】:

当我通过按单词搜索数据从 twitter 测试数据挖掘时遇到问题。

此代码错误UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

retweet = "-filter:retweets"
query = "#Thailand" + retweet 

df = pd.DataFrame(columns = ["create_at","user","location","text", "retweet_count", "favourite_count","hashtag","follower","source"])
for tweet in tweepy.Cursor(api.search, q = query,result_type="recent", tweet_mode='extended').items(100):
     
    entity_hashtag = tweet.entities.get('hashtags')
    hashtag = ""
    for i in range(0, len(entity_hashtag)):
        hashtag = hashtag + "/" + entity_hashtag[i]["text"]
    re_count = tweet.retweet_count
    create_at = tweet.created_at
    user = tweet.user.screen_name
    source = tweet.source
    location = tweet.user.location
    follower = tweet.user.followers_count

    try:
        text = tweet.retweeted_status.full_text
        fav_count = tweet.retweeted_status.favorite_count 

    except:     
        text = tweet.full_text
        fav_count = tweet.favorite_count  
    new_column = pd.Series([create_at,user,location,text, re_count, fav_count,hashtag,follower,source], index = df.columns)
    df = df.append(new_column, ignore_index = True)

df.to_csv(date_time+".csv")

为什么会有这个问题?

【问题讨论】:

  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
  • 哪些行有问题?添加有问题(不在评论中)
  • 通常的问题是文本有一些本机字符但系统尝试将其转换为ascii 而不是utf-8latin1cp1250,您必须手动添加此选项(即.encode="utf-8") 如果有可能会出现问题。
  • 我认为这个 df.to_csv(date_time+".csv")
  • 更好地显示完整的错误信息

标签: python pandas dataframe twitter ascii


【解决方案1】:

您没有提及您使用的是哪个版本的 Python,但我会在此处查看有关该主题的 Python 文档:https://www.python.org/dev/peps/pep-0263/(适用于 Python 2)

从那里:

要定义源代码编码,必须将魔术注释放在源文件中,作为文件的第一行或第二行,例如:

# coding=<encoding name>

或(使用流行编辑器认可的格式):

#!/usr/bin/python
# -*- coding: <encoding name> -*-

或:

#!/usr/bin/python
# vim: set fileencoding=<encoding name> :

我在某些情况下使用过这个版本:

#!/usr/bin/python
# -*- coding: <encoding name> -*-

也就是说,某些函数,尤其是 str() 不应该与 unicode 一起使用。更喜欢unicode()。使用第三方库时,您必须检查他们的文档,如果他们的文档有限,还可能查看其来源。

【讨论】:

【解决方案2】:

尝试在您的 scipt 开头将系统默认编码设置为 utf-8,以下应将默认编码设置为 utf-8 。

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

【讨论】:

  • 成功了,谢谢。
  • @ArifeenKundee 请点击勾选标记接受我的回答。谢谢
猜你喜欢
  • 2018-06-29
  • 2014-01-22
  • 2015-04-17
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多