首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将twitter数据流打印到文件中,每当我尝试时,都会出现unicode错误。

如何将twitter数据流打印到文件中,每当我尝试时,都会出现unicode错误。
EN

Stack Overflow用户
提问于 2020-01-19 17:44:39
回答 1查看 33关注 0票数 0

这是我从twitter检索数据的python代码。但是,当我试图将数据存储到gannie.txt时,我遇到了以下错误。

"D:\software\Anaconda\lib\encodings\cp1252.py",

第19行,在编码返回codecs.charmap_encode(输入,self.errors,encoding_table) UnicodeEncodeError:“charmap”编解码器不能编码位置5-6中的字符:字符映射到

对于这方面的任何帮助,我对本文的挖掘和我尝试用自然语言处理来建立情感分析项目是陌生的。

这是我的密码:

代码语言:javascript
复制
outF = open("gannie.txt", "a")
for tweet in tweets:
    #print(tweet.text)
    Tweet = tweet.text
                #Convert www.* or https?://* to URL
    Tweet = re.sub('((www\.[\s]+)|(https?://[^\s]+))','URL',Tweet)


    Tweet = re.sub('@[^\s]+','TWITTER_USER',Tweet)

                #Remove additional white spaces
    Tweet = re.sub('[\s]+', ' ', Tweet)

                #Replace #word with word Handling hashtags
    Tweet = re.sub(r'#([^\s]+)', r'\1', Tweet)

                #trim
    Tweet = Tweet.strip('\'"')

                #Deleting happy and sad face emoticon from the tweet 
    a = ':)'
    b = ':('
    Tweet = Tweet.replace(a,'')
    Tweet = Tweet.replace(b,'')

                #Deleting the Twitter @username tag and reTweets
    tag = 'TWITTER_USER' 
    rt = 'RT'
    url = 'URL'
    Tweet = Tweet.replace(tag,'')
    tweetCount+=1
    if rt in Tweet:
        continue
    Tweet = Tweet.replace(url,'')
    print(Tweet)
    outF.write(Tweet)
    outF.write("\n")
outF.close()
EN

回答 1

Stack Overflow用户

发布于 2020-01-20 06:25:42

我只需在打开文件行时添加encoding="utf-8“就可以得到答案。

以前:outF = open("gannie.txt", "a")

后:outF = open("gannie.txt", "a",encoding="utf-8")

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59812741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档