Decoding/Encoding 使用 sklearn load_files

Decoding/Encoding using sklearn load_files

我正在学习这里的教程 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' codec can't decode byte 0xd8 in position 561: invalid continuation byte

这是因为我的推文中有各种非标准文本吗?我没有对我的推文进行任何清理(我假设有一些库可以帮助清理这个词袋?)

编辑: 我使用 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()

您收到 UnicodeDecodeError,因为您的文件正在使用错误的文本编码进行解码。 如果这对您来说毫无意义,请确保您了解 Unicode 和文本编码的基础知识,例如。与 official 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'

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

一旦您认为自己知道写入文件所使用的编码方式,就可以在 load_files() 函数中指定:

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

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