Python中的UnicodeEncodeError

问题描述 投票:0回答:1

我遇到错误,我不知道该怎么办?!错误信息:在pandas._libs.writers.write_csv_rows中的文件“ pandas_libs \ writers.pyx”,第55行UnicodeEncodeError:'ascii'编解码器无法在位置147处编码字符u'\ u2026':序数不在范围(128)

import numpy as np
import pandas as pd
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import subjectivity
from nltk.sentiment import SentimentAnalyzer
from nltk.sentiment.util import *
import matplotlib.pyplot as mlpt
import tweepy
import csv
import pandas as pd
import random
import numpy as np
import pandas as pd
import re

consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)

fetch_tweets=tweepy.Cursor(api.search, q="#unitedAIRLINES",count=100, lang ="en",since="2018-9-13", tweet_mode="extended").items()
data=pd.DataFrame(data=[[tweet_info.created_at.date(),tweet_info.full_text]for tweet_info in fetch_tweets],columns=['Date','Tweets'])

data.to_csv("Tweets.csv")
cdata=pd.DataFrame(columns=['Date','Tweets'])
total=100
index=0
for index,row in data.iterrows():
    stre=row["Tweets"]
    my_new_string = re.sub('[^ a-zA-Z0-9]', '', stre)
    cdata.sort_index()
    cdata.set_value(index,'Date',row["Date"])
    cdata.set_value(index,'Tweets',my_new_string)
    index=index+1
#print(cdata.dtypes)
cdata

The error

python pandas csv decode encode
1个回答
0
投票

PANDAS正在处理Unicode数据,大概是在生成CSV输出文件时。

一种方法,如果您实际上不需要处理Unicode数据,则只需对数据进行转换即可获得所有ASCII码。

[另一种方法是在生成CSV输出文件之前对数据进行传递,以获取任何非ASCII字符的UTF-8编码。 (您可能需要在电子表格数据的单元格级别执行此操作。)

我在这里假设是Python3 ...

>>> s = "one, two, three, \u2026"
>>> print(s)
one, two, three, …
>>> ascii = str(s.encode("utf-8"))[2:-1]
>>> ascii
'one, two, three, \\xe2\\x80\\xa6'
>>> print(ascii)
one, two, three, \xe2\x80\xa6

另请参见:help()模块上的codecs

© www.soinside.com 2019 - 2024. All rights reserved.