【问题标题】:How to fix "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca" error?如何修复“UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca”错误?
【发布时间】:2021-09-23 05:18:22
【问题描述】:

我正在尝试通过我的程序运行一个包含大约 800 个单元格的 excel 文件。该程序完美地适用于大约 15 个单元格的文件。我得到的错误是

Traceback (most recent call last):
  File "/Users/first_lastname/Documents/CSVScraping.py", line 16, in <module>
    header = next(reader) #converts each row to a list
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 5214: invalid continuation byte

我的代码如下:

import csv
from textblob import TextBlob
import string

z = 10
poscounter = 0
negcounter = 0
neucounter = 0
totalsentences = 0


outfile = open('/Users/first_lastname/Desktop/WebScraping/TripAdvisor/Juneau/analyzedData.csv', 'w')

with open('/Users/first_lastname/Desktop/WebScraping/TripAdvisor/Juneau/tripadvisor_2021.csv', 'r') as infile:
    reader = csv.reader(infile)
    header = next(reader) #converts each row to a list
    #[rows][columns]

    for row in reader:
        trip_review = row[2]
        #print(trip_review)
        y = trip_review.lower()
        y = y.translate(str.maketrans('', '', string.punctuation))
        y1 = TextBlob(y)
        trip_sentiment = y1.sentiment.polarity
        xplitIt = y.split(" ")
        for something in xplitIt:
            if something == "crowded" or something == "busy" or something == "crowds" or something == "hate" or something == "hated":
                tripSentiment = -0.1
                break
            
        if trip_sentiment ==0:
            neucounter+=1
                
        elif trip_sentiment >0 and trip_sentiment <=1:
            poscounter+=1

        elif trip_sentiment == -0.1 or trip_sentiment < 0:
            negcounter+=1
            
        totalsentences = totalsentences + 1    
        line = "{};{}\n".format(trip_review, trip_sentiment)
        outfile.write(line)
outfile.close()

print(f"Positive Sentiment: {(poscounter/totalsentences) * 100} %")
print(f"Negative Sentiment: {(negcounter/totalsentences) * 100} %")
print(f"Neutral Sentiment: {(neucounter/totalsentences) * 100} %")
#print(totalsentences)

任何有关如何解决此问题的建议将不胜感激!!!!

【问题讨论】:

标签: python excel csv export-to-csv


【解决方案1】:

发现我所要做的就是在“with”函数参数中的 r 之后放入“encoding = latin-1”

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多