问题:
有人知道如何将这个b"it\\xe2\\x80\\x99s time to eat"
转换成这个it's time to eat
吗
更多详细信息&我的代码:
大家好,
我目前正在处理一个CSV文件,其中充满了带有UTF8字面量的行,例如:
b“它\xE2\x80\x99s吃饭时间”
最终的目标是得到这样的东西:
是时候吃东西了
为了实现这一点,我尝试使用以下代码:
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文件来解决此问题:
file_open = pd.read_csv("/Users/Downloads/tweets.csv", encoding = "utf-8")
它以以下方式打印出了示例行:
it\xe2\x80\x99s吃饭时间
我还尝试使用以下命令对这些行进行解码:
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
非常感谢您的帮助。
发布于 2018-06-25 01:22:42
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")
之后仍然有转义字符串,则可以执行以下操作:
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 (如果文件不太大):
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")
https://stackoverflow.com/questions/51011961
复制相似问题