首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >解码CSV文件中的UTF8文本

解码CSV文件中的UTF8文本
EN

Stack Overflow用户
提问于 2018-06-25 00:44:02
回答 1查看 536关注 0票数 1

问题:

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

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

大家好,

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

b“它\xE2\x80\x99s吃饭时间”

最终的目标是得到这样的东西:

是时候吃东西了

为了实现这一点,我尝试使用以下代码:

代码语言:javascript
复制
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吃饭时间

我已经尝试使用以下代码打开CSV文件来解决此问题:

代码语言:javascript
复制
file_open = pd.read_csv("/Users/Downloads/tweets.csv", encoding = "utf-8")

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

it\xe2\x80\x99s吃饭时间

我还尝试使用以下命令对这些行进行解码:

代码语言:javascript
复制
file_open["text"]=file_open["text"].str.decode('utf-8')

这给了我以下错误:

代码语言:javascript
复制
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

非常感谢您的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-25 01:22:42

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

通常,您可以将其转换为适当的Python3字符串,如下所示:

代码语言:javascript
复制
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")之后仍然有转义字符串,则可以执行以下操作:

代码语言:javascript
复制
pd.read_csv(..., encoding="unicode-escape")
# ...
# Now, your values will be strings but improperly decoded:
#    itâs time to eat
#
# So we encode to bytes then decode properly:
val = val.encode('latin1').decode('utf8')
print(val)   # it’s time to eat

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

代码语言:javascript
复制
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")
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51011961

复制
相关文章

相似问题

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