解码CSV-fi中的UTF8字面值

2024-09-23 04:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

有人知道我如何把这个b"it\\xe2\\x80\\x99s time to eat"转换成这个it's time to eat


更多详细信息和我的代码:

大家好

我目前正在处理一个CSV文件,其中充满了UTF8文本的行,例如:

b"it\xe2\x80\x99s time to eat"

最终目标是实现以下目标:

it's time to eat

为此,我尝试使用以下代码:

import pandas as pd


file_open = pd.read_csv("/Users/Downloads/tweets.csv")

file_open["text"]=file_open["text"].str.replace("b\'", "")

file_open["text"]=file_open["text"].str.encode('ascii').astype(str)

file_open["text"]=file_open["text"].str.replace("b\"", "")[:-1]

print(file_open["text"])

运行代码后,我作为示例的行打印为:

it\xe2\x80\x99s time to eat

我试着解决这个问题 使用以下代码打开CSV文件:

^{pr2}$

它以以下方式打印出示例行:

it\xe2\x80\x99s time to eat

我还试着用这个来解码行:

file_open["text"]=file_open["text"].str.decode('utf-8')

这给了我以下错误:

AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

事先非常感谢你的帮助。在


Tags: 文件csvto代码textpandastimeit
1条回答
网友
1楼 · 发布于 2024-09-23 04:23:07

b"it\\xe2\\x80\\x99s time to eat"听起来你的文件包含转义编码。在

通常,您可以将其转换为一个适当的Python3字符串,方法如下:

x = b"it\\xe2\\x80\\x99s time to eat"
x = x.decode('unicode-escape').encode('latin1').decode('utf8')
print(x)     # it’s time to eat

(使用.encode('latin1')explained here

因此,如果在使用pd.read_csv(..., encoding="utf8")之后仍然有转义字符串,可以执行以下操作:

^{pr2}$

但我认为最好是对整个文件执行此操作,而不是单独对每个值执行此操作,例如使用StringIO(如果文件不是太大):

from io import StringIO

# Read the csv file into a StringIO object
sio = StringIO()
with open('yourfile.csv', 'r', encoding='unicode-escape') as f:
    for line in f:
        line = line.encode('latin1').decode('utf8')
        sio.write(line)
sio.seek(0)    # Reset file pointer to the beginning

# Call read_csv, passing the StringIO object
df = pd.read_csv(sio, encoding="utf8")

相关问题 更多 >