0

我正在按照这里的教程 https://github.com/amueller/introduction_to_ml_with_python/blob/master/07-working-with-text-data.ipynb 了解机器学习和文本。

就我而言,我正在使用我下载的推文,正面和负面推文在他们使用的完全相同的目录结构中(试图学习情绪分析)。

在 iPython Notebook 中,我像他们一样加载我的数据:

tweets_train =load_files('Path to my training Tweets')

然后我尝试用 CountVectorizer 来拟合它们

vect = CountVectorizer().fit(text_train)

我明白了

UnicodeDecodeError:“utf-8”编解码器无法解码位置 561 中的字节 0xd8:无效的继续字节

这是因为我的推文中有各种非标准文本吗?我没有对我的推文进行任何清理(我假设有一些库可以帮助解决这个问题,以便让一袋单词起作用?)

编辑:我使用 Twython 下载推文的代码:

def get_tweets(user):
    twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
    user_timeline = twitter.get_user_timeline(screen_name=user,count=1)
    lis = user_timeline[0]['id']
    lis = [lis]
    for i in range(0, 16): ## iterate through all tweets
    ## tweet extract method with the last list item as the max_id
        user_timeline = twitter.get_user_timeline(screen_name=user,
        count=200, include_retweets=False, max_id=lis[-1])
        for tweet in user_timeline:
            lis.append(tweet['id']) ## append tweet id's
            text = str(tweet['text']).replace("'", "")
            text_file = open(user, "a")
            text_file.write(text)
            text_file.close()
4

1 回答 1

0

您收到 UnicodeDecodeError 是因为您的文件正在使用错误的文本编码进行解码。如果这对您没有任何意义,请确保您了解 Unicode 和文本编码的基础知识,例如。使用官方 Python Unicode HOWTO

首先,您需要找出用于将推文存储在磁盘上的编码。当您将它们保存到文本文件时,您使用了内置open函数而不指定编码。这意味着使用了系统的默认编码。例如,在交互式会话中检查这一点:

>>> f = open('/tmp/foo', 'a')
>>> f
<_io.TextIOWrapper name='/tmp/foo' mode='a' encoding='UTF-8'>

在这里可以看到,在我的本地环境中,默认编码设置为 UTF-8。您还可以使用以下命令直接检查默认编码

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

还有其他方法可以找出文件使用的编码。例如file,如果您碰巧在 Unix 平台上工作,那么 Unix 工具非常擅长猜测现有文件的编码。

一旦您认为您知道用于编写文件的编码,您可以在load_files()函数中指定它:

tweets_train = load_files('path to tweets', encoding='latin-1')

...如果您发现 Latin-1 是用于推文的编码;否则相应调整。

于 2017-05-26T13:28:15.763 回答