首页 > 解决方案 > 隐藏在字符串对象中的 Python 字节

问题描述

我有一个存储在 csv 文件中的字符串列表,其中一些看起来如下所示:

"b'the quick brown fox jumps over the lazy dog'"

Python 将其视为字符串,因此我无法使用 decode 来获取正确格式的内部字符串。我怎样才能做到这一点?作为最终结果,我想要:

"the quick brown fox jumps over the lazy dog"

我尝试过解码,以 、 和 模式加载文件'r''rb''rt'字符串str()上使用

这是我用来创建和填充 csv 文件的代码:

with open("scraped.csv", "a", newline='') as fd:
    print("writing data to csv file...")
    writer = csv.writer(fd)
    for comment in comments:
        writer.writerow([comment.encode("utf-8")])

标签: pythoncsv

解决方案


您首先错误地编写了 CSV 文件。如果要保证数据具体是UTF-8,传递encoding='utf-8'open调用,不要调用.encode("utf-8")字符串写入,直接传递字符串即可。

为了修复你已经得到的东西,因为你写了字符串形式的bytes文字,让 Python 用 解析文字ast.literal_eval,然后decode得到bytes

>>> import ast
>>> bytesform = ast.literal_eval("b'the quick brown fox jumps over the lazy dog'")
>>> strform = bytesform.decode('utf-8')
>>> print(strform)
the quick brown fox jumps over the lazy dog

推荐阅读