gpt4 book ai didi

python - 如何删除非utf 8代码并另存为csv文件python

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:10 24 4
gpt4 key购买 nike

我有一些亚马逊评论数据,我已经成功地从文本格式转换为 CSV 格式,现在问题是当我尝试使用 pandas 将其读入数据框时,我收到错误消息:UnicodeDecodeError:“utf-8”编解码器无法解码位置 13 中的字节 0xf8:起始字节无效

我知道评论原始数据中肯定有一些非 utf-8 的,我怎样才能删除非 UTF-8 并保存到另一个 CSV 文件?

谢谢!

编辑1:这是我将文本转换为 csv 的代码:

import csv
import string
INPUT_FILE_NAME = "small-movies.txt"
OUTPUT_FILE_NAME = "small-movies1.csv"
header = [
"product/productId",
"review/userId",
"review/profileName",
"review/helpfulness",
"review/score",
"review/time",
"review/summary",
"review/text"]
f = open(INPUT_FILE_NAME,encoding="utf-8")

outfile = open(OUTPUT_FILE_NAME,"w")

outfile.write(",".join(header) + "\n")
currentLine = []
for line in f:

line = line.strip()
#need to reomve the , so that the comment review text won't be in many columns
line = line.replace(',','')

if line == "":
outfile.write(",".join(currentLine))
outfile.write("\n")
currentLine = []
continue
parts = line.split(":",1)
currentLine.append(parts[1])

if currentLine != []:
outfile.write(",".join(currentLine))
f.close()
outfile.close()

编辑2:

感谢所有试图帮助我的人。所以我通过修改代码中的输出格式解决了这个问题:

 outfile = open(OUTPUT_FILE_NAME,"w",encoding="utf-8")

最佳答案

如果输入文件不是 utf-8 编码的,尝试以 utf-8 读取它可能不是一个好主意...

基本上有两种方法来处理解码错误:

  • 使用可以接受任何字节的字符集,例如 iso-8859-15,也称为 latin9
  • 如果输出应为 utf-8 但包含错误,请使用 errors=ignore -> 静默删除非 utf-8 字符,或 errors=replace -> 替换非带有替换标记的 utf-8 字符(通常是 ?)

例如:

f = open(INPUT_FILE_NAME,encoding="latin9")

f = open(INPUT_FILE_NAME,encoding="utf-8", errors='replace')

关于python - 如何删除非utf 8代码并另存为csv文件python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32733615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com