我有一个dataframe,多个列和一个列包含从各种链接中刮来的文本。我试图将该列转换为utf-8,但它没有工作。
以下是我的做法:
df = pd.read_excel('data.xlsx',encoding=sys.getfilesystemencoding())
df['text'] = df['text'].apply(lambda x: x.encode('utf-8').strip())
print(df['text'])我收到了一些ascii代码的短信:
B‘b’#谢谢,它\xE2\x80\x99很好.
df = pd.read_excel('data.xlsx',encoding=sys.getfilesystemencoding())
df['text'] = df['text']
print(df['text'])我收到短信:
B‘#谢谢你,很高兴能在这里.
df['text'] = df['text'].apply(lambda x: x.decode('utf-8').strip())AttributeError:'str‘对象没有属性'decode’
我尝试了2-3种方法,但都没成功。有别的选择吗?
使用Python3.6和jupyter笔记本。
发布于 2020-03-12 17:24:08
假设您为第二行df['text'] = df['text']以'结尾的示例所写的内容。换句话说,b'#Thank you, it\xe2\x80\x99s good to be here....'
由于某些原因,您的字节码已经被转换为字符串,因为您在尝试解码时看到了AttributeError: 'str' object has no attribute 'decode'。(理想情况下,最好不要陷入这种情况,请参阅这里获得一些看起来相关的建议。唉,用你所拥有的.)
我认为在这一点上,您可以在字符串的开头删除b',在远端删除',并删除类型转换为字节码。请注意,这将导致反斜杠被转义,因此除了现在以正确的方式将字节代码解码为字符串之外,还需要处理这些问题。使用基于这里的方法,您可以对字节码进行转义和解码。
将它与显示为df['text']的内容结合起来(类似于注释中的@rolf82 82),当df['text'] = df['text']在开始时是一个字符串时,您所拥有的转换如下:
a = "b'#Thank you, it\xe2\x80\x99s good to be here'"
# But we only want the parts between the ''.
s = bytes(r"#Thank you, it\xe2\x80\x99s good to be here","utf-8")
import codecs
print(codecs.escape_decode(s)[0].decode("utf-8"))这意味着:
#Thank you, it’s good to be here这就是我们想要的。
现在,将其与Pandas集成将需要额外的东西,因为我们不能简单地说这是一个原始字符串,在前面添加r。基于这里和这里,似乎可以使用前面的r将原始字符串转换为.encode('unicode-escape').decode(),如下所示:
"#Thank you, it\xe2\x80\x99s good to be here".encode('unicode-escape').decode()所以,把所有这些都放在一起,我会把你的第二行替换为:
import codecs
df['text'] = df['text'].apply(lambda x: codecs.escape_decode(bytes(x[2:-1].encode('unicode-escape').decode(), "utf-8"))[0].decode('utf-8').strip())如果这不起作用,也可以尝试在.decode()之后删除.encode('unicode-escape'),即:
```python进口码
df‘’text‘=df’‘text’.(lambda x: codecs.escape_decode(bytes(x2:-1.encode('unicode-escape'),“utf-8”).decode(‘utf-8’).strip()
https://stackoverflow.com/questions/60640682
复制相似问题