python - 隐藏在字符串对象中的 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")])
解决方案
您首先错误地编写了 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
推荐阅读
- xamarin - Xamarin 条目在删除最后一个字符时不会引发绑定项目属性的设置器
- docker - 在 macbook 上使用 docker 安装 sql server 时出错
- android - Android 用 Livedata 和 ViewModel 替换 Greenrobot 事件机制
- python - 如何在火花中合并数据框中的列表
- data-structures - 通过删除给定元素并将剩余位置填充 1 来重新排列数组
- javascript - 仅在月份选择器中获取当前月份,其他月份必须禁用
- numpy - RuntimeWarning:使用 ODEINT 和 solve_bvp 求解 Poisson-Boltzmann 方程时在 sinh 中遇到溢出
- reactjs - 反应组件无法找到我的 CSS 类
- json - 将 Typescript 与 JSON 结合使用的模式是什么?
- javascript - 在 HTML 中按 Javascript 搜索过滤器